Can't extract string from database sql - sql

My aim is to test if the user and password inserted, existed in Table1.
However, if I typed (pink,floyd) which exists in the database count still null and it appears the message "user doesn't exist".
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
String user=f_user.getText().trim();
String pass=f_pass.getText().trim();
String sql="select user, pass from \"Table1\" where user='"+user+"' and pass='"+pass+"'";
rs=stat.executeQuery(sql);
int count=0;
while(rs.next()){
count++;
}
if (count==0) JOptionPane.showMessageDialog(null, "user doesn't exist");
else JOptionPane.showMessageDialog(null, "acces permitted");
} catch ( Exception ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here's my database :

First problem you had - cos you updated was that your sql was invalid. you're missing FROM.

You had created table1 but sql is from table2.

It turns that the stocked user and pass parameters in Table1 hasn't the same length of input parameters . So , we need to change :
String sql="select user, pass from \"Table1\" where user='"+user+"' and pass='"+pass+"'";
to
String sql="select * from \"Table1\" where trim(\"user\")= '"+user+"' and trim(\"pass\")= '"+pass+"'";

Related

Netbeans,SQL query after connection

After successful connection with sql server (using wamp), ive added a simple table with 1 column and one value, so im trying to take that value and update the jlist. It shows no error and it doesnt work,forgive me if im done someting stupid. (Also im writing this inside a jcombobox event handler)
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
String a = null;
String que="SELECT * FROM game";
Connection dn=null;
Statement st=null;
ResultSet sm=null;
String db="jdbc:mysql://localhost:3306/project";
try{
dn=DriverManager.getConnection(db, "user", "");
st=dn.prepareStatement(que);
sm=st.executeQuery(que);
while(sm.next())
{
a=sm.getString(1);
}
DefaultListModel n=new DefaultListModel();
n.addElement(a);
jList1.setModel(n);
}
catch(SQLException e)
{
}
}

Check that a value on a webpage is numerical in selenium webdriver

When checking to see if a price is given on a webpage, I don't want to check the exact value (as that's subject to change), I first want to check that the page object exists (no error, etc.) and then that it's returning a numerical value.
Is this possible?
With C#
private IWebElement priceElement = driver.FindElement(By.Id("price_value"));
public bool PriceObjectValidation()
{
decimal outDecim;
try
{
string str = priceElement.Text;
bool isDecimal = decimal.TryParse(str, out outDecim);
return isDecimal;
}
catch (NoSuchElementException e)
{
throw new Exception("Price element is not found");
}
catch (FormatException)
{
return false;
}
}
In your Test Script you can use
Assert.True(PriceObjectValidation(), "Price element is not numeric value");

Data is Null. This method or property cannot be called on null values.

Hi I have nulls in a table that I will use to populate a combo box. I am not sure how to do this. When I run the below code I get the error: Data is Null. This method or property cannot be called on null values.
private void code()
{
sc.Close();
try
{
sc.Open();
string Query = "SELECT * from CodeTable";
SqlCommand createCommand = new SqlCommand(Query, sc);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
String code = dr.GetString(1);
if (!cbDevices.Items.Contains(code))
{
cbDevices.Items.Add(code);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You can filter out null using IsDbNull .
if (!dr.IsDbNull(1))
{
String code = dr.GetString(1);
if cbDevices.Items.Contains(code))
{
cbDevices.Items.Add(code);
}
}
Easiest way is just to filter them out in your SQL:
"SELECT * from CodeTable WHERE code IS NOT NULL"
I'm assuming that the field name is code based on your sample, but you can adjust appropriately.

SAP JCo RETURN Table empty when using TransactionID

I'm using the JCo Library to access SAP standard BAPI. Well everything is also working except that the RETURN Table is always empty when I use the TID (TransactionID).
When I just remove the TID, I get the RETURN table filled with Warnings etc. But unfortunately I need to use the TID for the transactional BAPI, otherwise the changes are not commited.
Why is the RETURN TABLE empty when using TID?
Or how must I commit changes to a transactional BAPI?
Here speudo-code of a BAPI access:
import com.sap.conn.jco.*;
import org.apache.commons.logging.*;
public class BapiSample {
private static final Log logger = LogFactory.getLog(BapiSample.class);
private static final String CLIENT = "400";
private static final String INSTITUTION = "1000";
protected JCoDestination destination;
public BapiSample() {
this.destination = getDestination("mySAPConfig.properties");
}
public void execute() {
String tid = null;
try {
tid = destination.createTID();
JCoFunction function = destination.getRepository().getFunction("BAPI_PATCASE_CHANGEOUTPATVISIT");
function.getImportParameterList().setValue("CLIENT", CLIENT);
function.getImportParameterList().setValue("INSTITUTION", INSTITUTION);
function.getImportParameterList().setValue("MOVEMNT_SEQNO", "0001");
// Here we will then all parameters of the BAPI....
// ...
// Now the execute
function.execute(destination, tid);
// And getting the RETURN Table. !!! THIS IS ALWAYS EMPTY!
JCoTable returnTable = function.getTableParameterList().getTable("RETURN");
int numRows = returnTable.getNumRows();
for (int i = 0; i < numRows; i++) {
returnTable.setRow(i);
logger.info("RETURN VALUE: " + returnTable.getString("MESSAGE"));
}
JCoFunction commit = destination.getRepository().getFunction("BAPI_TRANSACTION_COMMIT");
commit.execute(destination, tid);
destination.confirmTID(tid);
} catch (Throwable ex) {
try {
if (destination != null) {
JCoFunction rollback = destination.getRepository().getFunction("BAPI_TRANSACTION_ROLLBACK");
rollback.execute(destination, tid);
}
} catch (Throwable t1) {
}
}
}
protected static JCoDestination getDestination(String fileName) {
JCoDestination result = null;
try {
result = JCoDestinationManager.getDestination(fileName);
} catch (Exception ex) {
logger.error("Error during destination resolution", ex);
}
return result;
}
}
UPDATE 10.01.2013: I was finally able to get both, RETURN table filled and Inputs commited. Solution is to do just both, a commit without TID, get the RETURN table and then making again a commit with TID.
Very very strange, but maybe the correct usage of the JCo Commits. Can someone explain this to me?
I was able to get both, RETURN table filled and Inputs commited.
Solution is to do just both, a commit without TID, get the RETURN table and then making again a commit with TID.
You should not call execute method 2 times it will incremenmt sequence number
You should use begin and end method in JCoContext class.
If you call begin method at the beginning of the process, the data will be updated and message will be returned.
Here is the sample code.
JCoDestination destination = JCoDestinationManager.getDestination("");
try
{
JCoContext.begin(destination);
function.execute(destination)
function.execute(destination)
}
catch (AbapException ex)
{
...
}
catch (JCoException ex)
{
...
}
catch (Exception ex)
{
...
}
finally
{
JCoContext.end(destination);
}
you can reffer the further information from this URL.
http://www.finereporthelp.com/download/SAP/sapjco3_linux_32bit/javadoc/com/sap/conn/jco/JCoContext.html

Why can I not get any results from this rather trivial query?

I'm trying to get results from a rather trivial query, and write out those results on a jsp page. Running Glassfish 3.1, using Netbeans. When I run the project, I get an empty list returned from the routine.
When I right click the table in Services and hit View Data, I can see the table is populated, and when I copy and past the query into the SQL Command window and run it, it gives the expected list of length 2.
There are a few similar questions (like this one), none of which seemed to be of much help. I am new at this, so I may not have understood a solution to one of the other questions.
There are a lot of factors at play here, and I'm not really sure what to include. I have included the routine doing the query, the JSP Code calling that routine, the entity class I'm using, and the output of the server log that I get when the project is run. If more information is needed, let me know and I'll put it up.
I really appreciate any help.
Griff
Routine doing the query:
public static LinkedList<String> getCategories(EntityManager entityManager) {
try {
Query query = entityManager.createQuery(
"SELECT DISTINCT i.category from ItemEntity i");
List resultList = query.getResultList();
if (!resultList.isEmpty()) {
return new LinkedList<String>(resultList);
}
} catch(Exception e) {
System.out.println(e);
} finally {
return new LinkedList<String>();
}
}
The JSP Code calling the routine:
<body>
<h1>Store</h1>
<h2>Categories</h2>
<%
Context environmentContext
= (Context) new InitialContext().lookup("java:comp/env");
EntityManager entityManager
= (EntityManager) environmentContext.lookup("persistence/dbunit");
LinkedList<String> categories = DataBase.getCategories(entityManager);
ListIterator<String> categoryIterator = categories.listIterator();
String category = "";
%>
<form action="category.jsp">
<% while (categoryIterator.hasNext()) { %>
<% category = categoryIterator.next(); %>
<input type="submit" class="submitButtonAsLink" value="<%= category %>" name="<%= category %>" /><br />
<% } %>
</form>
</body>
ItemEntity.java:
#Entity
public class ItemEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id #GeneratedValue(strategy = GenerationType.AUTO)
private String id;
private String title;
private String longDescription;
private double cost;
private String category;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ItemEntity)) {
return false;
}
ItemEntity other = (ItemEntity) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "store.model.entities.ItemTable[ id=" + id + " ]";
}
//getters and setters omitted.
//There are getters and setters for every field except id.
}
Server Log:
INFO: file:/Users/griffgeorge/Dropbox/school/design-arch/labs/Lab4Exercise/build/web/WEB-INF/classes/_Lab4ExercisePU logout successful
INFO: Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
INFO: EclipseLink, version: Eclipse Persistence Services - 2.3.0.v20110604-r9504
INFO: file:/Users/griffgeorge/Dropbox/school/design-arch/labs/Lab4Exercise/build/web/WEB-INF/classes/_Lab4ExercisePU login successful
WARNING: Multiple [2] JMX MBeanServer instances exist, we will use the server at index [0] : [com.sun.enterprise.v3.admin.DynamicInterceptor#1ed957d].
WARNING: JMX MBeanServer in use: [com.sun.enterprise.v3.admin.DynamicInterceptor#1ed957d] from index [0]
WARNING: JMX MBeanServer in use: [com.sun.jmx.mbeanserver.JmxMBeanServer#1a84f3c] from index [1]
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE ITEMENTITY (ID VARCHAR(255) NOT NULL, CATEGORY VARCHAR(255), COST FLOAT, LONGDESCRIPTION VARCHAR(255), TITLE VARCHAR(255), PRIMARY KEY (ID))": java.sql.SQLException: Table/View 'ITEMENTITY' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "CREATE TABLE SEQUENCE (SEQ_NAME VARCHAR(50) NOT NULL, SEQ_COUNT DECIMAL(15), PRIMARY KEY (SEQ_NAME))": java.sql.SQLException: Table/View 'SEQUENCE' already exists in Schema 'APP'.
WARNING: PER01000: Got SQLException executing statement "INSERT INTO SEQUENCE(SEQ_NAME, SEQ_COUNT) values ('SEQ_GEN', 0)": java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'SQL111012114449870' defined on 'SEQUENCE'.
INFO: WEB0671: Loading application [Lab4Exercise] at [/Lab4Exercise]
Your getCategories() method always returns an empty list, because the return in finally always runs (even after the first return).
You don't need a finally clause there at all. You can simplify to this
public static LinkedList<String> getCategories(EntityManager entityManager) {
try {
Query query = entityManager.createQuery(
"SELECT DISTINCT i.category from ItemEntity i");
return new LinkedList<String>(query.getResultList());
} catch(Exception e) {
System.out.println(e);
return new LinkedList<String>();
}
}
If your query.getResultList() is not empty, then it returns a non empty linked list of strings.
If your query.getResultList() is empty, then it returns an empty linked list of strings.
If an exception happens then it returns an empty list.
As you had before, it was always returning an empty list, even if your query was returning data.
To prove that the return in finally is the one that gets through, take a look at this
public class TestFinally {
public static void main(String[] args) {
System.out.println(TestFinally.test());
}
public static int test() {
try {
return 1;
} finally {
return 0;
}
}
}
returns
0
how about your persistence.xml? is that pointing to the datasource you expect? and then is that datasource pointing to the connection pool you expect?