Reputation: 105
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;
}
Hi, here is my code and the section of the database I am trying to grab: http://prntscr.com/ezbomi. I want the ID but it is returning null. I'm thinking it is because of the query - any idea?
Upvotes: 0
Views: 469
Reputation: 562
Try this. Dropped the quotes. Unless you have a good reason not to, you should always make use of prepared statements. Any particular reason you tried to access the 2nd element from the ResultSet?
private UUID getClientID(String username) {
try {
//drop the extra quotes in the SQL statement
String query = "SELECT id FROM client_table WHERE username = ?";
//added prepared statement
PreparedStatement stmt = connection.prepareStatement(query);
stmt.setString(1, username);
ResultSet rs = stmt.getResultSet();
//use 1 to access the first result from the result set
return UUID.fromString(rs.getString(1));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Upvotes: 0
Reputation: 347204
ResultSet#next
to get the next row from the ResultSet
, if one exists1
instead of 2
when getting the column value, as you've only requested a single column and column indices start at 1
PreparedStatements
, parameters and bind the value to the statementtry-with-resources
to manage your resources and make sure you clean them up when you're doneException
rather than catching it, it would having more meaning than just returning null
For example
try (PreparedStatement stmt = connection.prepareStatement("SELECT id FROM `client_table` WHERE username=?")) {
stmt.setString(1, username);
ResultSet rs = stmt.getResultSet();
if (rs.next()) {
return UUID.fromString(rs.getString(1));
}
}
Have a look at:
for more details
Upvotes: 1
Reputation: 131
You should move your ResultSet cursor before getting the data. The cursor is initially pointed before the head.
rs.next();
return UUID.fromString(rs.getString(2));
Upvotes: 0