J. Doe
J. Doe

Reputation: 105

Getting ID from database (my sql) returns null

    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

Answers (3)

KUSH42
KUSH42

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

MadProgrammer
MadProgrammer

Reputation: 347204

  • You need to call (and check the result of) ResultSet#next to get the next row from the ResultSet, if one exists
  • You need to use 1 instead of 2 when getting the column value, as you've only requested a single column and column indices start at 1
  • You should make proper use of PreparedStatements, parameters and bind the value to the statement
  • You should make use of try-with-resources to manage your resources and make sure you clean them up when you're done
  • I'd consider throwing the Exception 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

neeranzan
neeranzan

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

Related Questions