2015-11-12 64 views
0
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); 
} 

我正在使用JDBC Java從數據庫中查詢名稱,但這次它出現錯誤,我不知道爲什麼。我之前使用過Java JDBC。我可以連接到數據庫,但查詢似乎不工作? Id列是整數10位數字。Java JDBC結果集錯誤,但是爲什麼?

"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)" 
+2

調用'myRs1.next()'從它 –

+0

http://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html –

回答

4

當您嘗試訪問某些內容而不移動光標時,會出現這種錯誤。在獲取String之前嘗試將myRs1.next();

+0

它的作品閱讀之前將光標移動到第一行,謝謝! –

0

內部對於循環,當得到ResultSet時,您需要檢查myRs1.next()如下所述。

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); 
    } 
}