Java JDBC result set error, but why? [duplicate]

2019-09-10 04:10发布

问题:

This question already has an answer here:

  • ResultSet exception - before start of result set 6 answers
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","user","pass");
Statement myStmt1 = myConn.createStatement();
System.out.println("connected");

for(int i=1; i<1375462;i++){
    ResultSet myRs1 = myStmt1.executeQuery("SELECT Name FROM table WHERE id ="+i);

    String Name = myRs1.getString("Name");
    System.out.print(i);
    System.out.println("Name:"+Name);
}

I'm using JDBC Java to query the name from database but this time it got an error and I don't know why. I have used Java JDBC before. I can connect to database but the query seem like not working? Id column is integer 10 digit.

"run: connected java.sql.SQLException: Before start of result set
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:959)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:862)
    at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:790)
    at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5244)
    at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5167)
    at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5206)"

回答1:

This kind of error appears when you try to access something without moving cursor. Try to put myRs1.next(); before getting String.



回答2:

Inside for loop, when getting the ResultSet, you need a check myRs1.next() as described below.

for(int i=1; i<1375462;i++){
    ResultSet myRs1 = myStmt1.executeQuery("SELECT Name FROM table WHERE id ="+i);
    while(myRs1.next()) {
        String Name = myRs1.getString("Name");
        System.out.print(i);
        System.out.println("Name:"+Name);
    }
}


标签: java jdbc