【发布时间】:2015-07-03 16:41:39
【问题描述】:
我的 java 代码出现异常。我想从给定的名称中获取 Id,在这种情况下 Id 是主键。当我在工作台中查询时,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)
【问题讨论】: