Ethan Ye
Ethan Ye

Reputation: 29

JDBC and MySQL Statement and ResultSet error

I am trying to run the following code:

Scanner input = new Scanner(System.in);
ResultSet rs = null;
System.out.print("Username: ");
String username = input.next();
System.out.print("\nPassword: ");
String pword = input.next();
String stmt = "SELECT * FROM accounts WHERE username = '"+username+"' AND password = '"+pword+"' ";
Statement s = con.createStatement();      // con = Connection object
rs = s.executeQuery(stmt);
if(rs.absolute(1)) {
    System.out.println("LOGIN SUCCESSFUL");
}
else {
    System.out.println("INVALID LOGIN");
}

However, I end up with the following error:

java.sql.SQLException: Operation not allowed for a result set of type ResultSet.TYPE_FORWARD_ONLY.
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.result.ResultSetImpl.absolute(ResultSetImpl.java:391)
    at practice.JDBCtester.login(JDBCtester.java:36)
    at practice.JDBCtester.main(JDBCtester.java:17)

Could someone explain the problem with my code?

Upvotes: 0

Views: 283

Answers (2)

The Impaler
The Impaler

Reputation: 48750

Instead of using absolute() you can just verify at least one row was returned. For example you can do:

rs = s.executeQuery(stmt);
if (rs.next()) {
  System.out.println("LOGIN SUCCESSFUL");
}
else {
  System.out.println("INVALID LOGIN");
}

absolute() is an advanced method useful for reading, re-reading, and updating special types of result sets. Your result set is a simple one.

Upvotes: 3

Mark Rotteveel
Mark Rotteveel

Reputation: 108941

As documented in the ResultSet.absolute(int):

Throws:
  SQLException - if a database access error occurs; this method is called on a closed result set or the result set type is TYPE_FORWARD_ONLY

In most situations, the default result set type is TYPE_FORWARD_ONLY, so the absolute method is not supported.

Instead use ResultSet.next() to check if there is at least one row.

As I also commented, your current code is highly insecure. Don't concatenate values into a query string (especially not values obtained from a user), as this makes your code vulnerable to SQL injection. Instead use a prepared statement with parameter placeholders. Also don't store plaintext passwords, but use an appropriate password hashing algorithm.

Upvotes: 1

Related Questions