I'm having trouble getting data from a ResultSet
object. Here is my code:
String sql = "SELECT type FROM node WHERE nid = ?";
PreparedStatement prep = conn.prepareStatement(sql);
int meetNID = Integer.parseInt(node.get(BoutField.field_meet_nid));
prep.setInt(1, meetNID);
ResultSet result = prep.executeQuery();
result.beforeFirst();
String foundType = result.getString(1);
if (! foundType.equals("meet")) {
throw new IllegalArgumentException(String.format("Node %d must be of type 'meet', but was %s", meetNID, foundType));
}
The error trace:
Exception in thread "main" java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1072)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:986)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:981)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:841)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5656)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5576)
at nth.cumf3.nodeImport.Validator.validate(Validator.java:43)
at nth.cumf3.nodeImport.Main.main(Main.java:38)
What am I doing wrong here?
Basically you are positioning the cursor before the first row and then requesting data. You need to move the cursor to the first row.
result.next();
String foundType = result.getString(1);
It is common to do this in an if statement or loop.
if(result.next()){
foundType = result.getString(1);
}
Every answer uses .next()
or uses .beforeFirst()
and then .next()
. But why not this:
result.first();
So You just set the pointer to the first record and go from there. It's available since java 1.2 and I just wanted to mention this for anyone whose ResultSet
exists of one specific record.
You have to do a result.next() before you can access the result. It's a very common idiom to do
ResultSet rs = stmt.executeQuery();
while (rs.next())
{
int foo = rs.getInt(1);
...
}
You have to call next()
before you can start reading values from the first row. beforeFirst
puts the cursor before the first row, so there's no data to read.
最好创建一个包含所有查询方法的类,包括在不同的包中,这样就不必在每个类中键入所有过程,而只需从该类中调用该方法。
You need to move the pointer to the first row, before asking for data:
result.beforeFirst();
result.next();
String foundType = result.getString(1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.