简体   繁体   中英

Why does this Query return NULL?

I have a derby users database which I query, when the user clicks login on the application.

However, when I query the users table with the parameter [user] derby returns a null Object instead of the record it ought to return.

Here is my code:

String ssql = "SELECT * FROM USERS WHERE UNAME LIKE ?";
   try{
       DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
       con = DriverManager.getConnection(url);
       sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
       sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
       sql.executeQuery();
       ResultSet rs = sql.getGeneratedKeys();
           try{
              while (rs.next()) {
                 if(rs.getString("PW").toCharArray().equals(txt_password.getPassword())){
                     sql.close();
                     con.close();
                     return true;
                  }
             } catch (NPE ...) {...}
    }

I tried it multiple times wit a test user with both the pw and the username set to "test"; but I always get the same error. Why is the recordset always Null?

Thanks for your help :)

The documentation says

ResultSet getGeneratedKeys() throws SQLException

Retrieves any auto-generated keys created as a result of executing this Statement object.

If this Statement object did not generate any keys, an empty ResultSet object is returned.

Your select statement isn't generating any keys that's why it's returning an empty ResultSet. You aren't inserting anything hence no keys are being generated.

You can try ResultSet rs = sql.executeQuery(); . It should work.

You are using it in wrong way.

The generated keys concept should be used only in the case DML of insert type query but not in the case of select query.

select simply select the rows from the table. In this case there is no chance of any keys getting generated.

In the case of insert query if any column is configured as auto increment or kind of functionality then some keys will get generated. These keys can be caught using Statement.RETURN_GENERATED_KEYS in java.

As you are using select query there is no need of using Statement.RETURN_GENERATED_KEYS .

You just modify below lines and everything will be fine.

sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();

with

sql = con.prepareStatement( ssql );
sql.setString( 1, cbox_chooseUser.getSelectedItem().toString() );
ResultSet rs = sql.executeQuery();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM