king
king

Reputation: 33

java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid cursor state

I created a simple application that compares a database value with a textfield value, but when I execute the project it gives me the following Exception:

java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid cursor state

This is the code I'm using:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
   String dataSource ="testDb";
   String U="jdbc:odbc:"+dataSource;
   try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      Connection con=DriverManager.getConnection(U,"","");

      PreparedStatement s=con.prepareStatement("Select * from student");
      ResultSet s1=s.executeQuery();


      String textField;
      textField=jTextField1.getText();
      String database =s1.getString(1);
      if(textField.equals(database)) { 
         System.out.println("ok");
      } else {
         System.out.println("Not ok");
      }
   } catch(Exception ex) {
      System.out.println("THE EXCEPTION IS"+ex);
   }
}

What could be the cause if this Exception?

Upvotes: 3

Views: 22565

Answers (3)

Kal
Kal

Reputation: 24910

When you do s.executeQuery(), the initial position of the ResultSet is BEFORE the first row.

You have to do rs.next() to advance it to the first row.

Enclose your ResultSet processing in a if ( s1.next() ) {} block

Upvotes: 6

hamzah
hamzah

Reputation: 11

you need to make Resultset pointer to the first row by using next function and then make the compare that you need between the database value and the textField value i hope this helpful.

Upvotes: 0

Srikanth Venkatesh
Srikanth Venkatesh

Reputation: 2812

Try like this..

        ResultSet s1=s.executeQuery();
        String database=null;
        if(s1.next())
        {
          database =s1.getString(1);
        }
  • When s1.getString(1) is used without s1.next().
  • s1 is not pointing to first row.That's why the exception

Upvotes: -1

Related Questions