简体   繁体   中英

MySQL returning NPE getting an ID from a table (as a string)

private UUID getClientID(String username) {
    try {
        String query = "SELECT id FROM `client_table` WHERE username=" + username;
        stmt = connection.prepareStatement(query);
        ResultSet rs = stmt.getResultSet();
        return UUID.fromString(rs.getString(2));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

The table:

id username password create_date

id = c235a95d-58e7-4454-90ea-58396a00a3c5 username = myUsername password = [BLOB - 16 B] create_date = Fri Apr 28 09:34:49 BST 2017

So why would it return null? I think I am doing something wrong with the ResultSet .

String should be between two 'username' and you already use PreparedStatement so instead use :

String query = "SELECT id FROM `client_table` WHERE username= ?";
stmt = connection.prepareStatement(query);
stmt.setString(1, username);
ResultSet rs = stmt.executeQuery();
if(rs.next()){
   return UUID.fromString(rs.getString(1));
}else{
   return null;//id not found
}

Note

  1. Your query return just one field, so it is wrong to use rs.getString(2) there are no second field
  2. You have to execute the statement, then use rs.next() to get results

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