Search code examples
javamysqljdbcresultset

Getting primary key value from resultset by using Java variable with SQL WHERE clause


I know its not great practise at all to use techniques like this as it is prone to SQL injections, but for speed and testing this is currently how I am doing it. I am creating a program which saves a username, ip and a database name to another database. However when I try and perform a statement like so:

ResultSet rs = stmt.executeQuery("SELECT LoginID, IPAddress FROM slavelogins WHERE IPAddress = '" + inputString + "';");
            String ClientID = String.valueOf(rs.getInt(1));
            System.out.println("Client ID: " + ClientID);
        } catch (SQLException err) {
            System.err.println("Error retrieving client id, please continue later!" + err);
            System.exit(0);

I then run into an error which says the value is before the start of resultset, I believe this means there is no data retrieved from the database, is there a way to fix this or a way around this or an easier way which I am not realising?

P.S LoginID is a primary key if that creates any problems.

The code above retrieves the loginid and displays it to the user as 'ClientID: ' + rs.getInt(1) where rs.getInt should be the loginID.

I have also seen posts about using placeholders in preparedstatements but I haven't seen anything regarding a select query in a normal statement.

The error message:

Error retrieving client id, please continue later! java.sql.SQLException: Before start of result set


Solution

  • You can think of the ResultSet as a cursor over the rows you've queried. Whatever its position may be, you can use next() to check if there's another row there, and move the cursor to it.

    The first row of the result is no different - a ResultSet start before the first row, and you need to use next() to move to that row:

    if (rs.next()) {
        String clientID = String.valueOf(rs.getInt(1));
        System.out.println("Client ID: " + clientID);
    } else {
        System.out.println("No such client");
    }