结果集异常 - 在结果集开始之前

2022-08-31 11:34:55

我无法从 ResultSet 对象获取数据。这是我的代码:

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

错误跟踪:

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)

我在这里做错了什么?


答案 1

基本上,您将游标定位在第一行之前,然后请求数据。您需要将游标移动到第一行。

 result.next();
 String foundType = result.getString(1);

通常在 if 语句或循环中执行此操作。

if(result.next()){
   foundType = result.getString(1);
}

答案 2

您必须先执行 result.next() 操作,然后才能访问该结果。这是一个非常常见的成语

ResultSet rs = stmt.executeQuery();
while (rs.next())
{
   int foo = rs.getInt(1);
   ...
}

推荐