2015-07-03 13 views
0

我在我的java代碼中收到異常。我想從給定的名字得到Id,在這種情況下Id是主鍵。 MySQL查詢工作,當我查詢在工作臺:通過Java中的給定名稱參數從mysql獲取主鍵

SELECT client_id FROM client where concat(lastname, " ", firstname) = "Hudson Kate"; 

但是當我在javacode使用此查詢:

public int getClientID(String name) throws SQLException{ 
     int ID = 0; 
     PreparedStatement myprepStmt = null; 
     ResultSet myRs = null; 

     try { 
      myprepStmt = myConn.prepareStatement("SELECT client_id FROM client " 
        + "where concat(lastname, \" \", firstname) =?"); 

      myprepStmt.setString(1, name); 
      myRs = myprepStmt.executeQuery(); 

      ID = myRs.getInt("client_id"); //this creates a problem 

     } catch (Exception e) { 
      // TODO: handle exception 
      e.printStackTrace(); 
     } 
     finally { 
      close(myprepStmt, myRs); 
     } 

     return ID; 
    } 

我得到這個異常:

java.sql.SQLException: Before start of result set 
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998) 
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:937) 
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926) 
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:872) 
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:787) 
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2460) 
at com.mysql.jdbc.ResultSetImpl.getInt(ResultSetImpl.java:2571) 
at DBConnection.getClientID(DBConnection.java:135) 
at sample.main(sample.java:38) 

回答

相關問題