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

Nic*_*ner 69 java jdbc

我在从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));
    }
Run Code Online (Sandbox Code Playgroud)

错误跟踪:

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)
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?

Vin*_*nie 146

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

 result.next();
 String foundType = result.getString(1);
Run Code Online (Sandbox Code Playgroud)

在if语句或循环中执行此操作是很常见的.

if(result.next()){
   foundType = result.getString(1);
}
Run Code Online (Sandbox Code Playgroud)

  • 也许在这种情况下使用 `result.first()`。 (2认同)

Mmy*_*low 9

每个答案都使用.next()或使用.beforeFirst()然后使用.next().但为什么不这样:

result.first();
Run Code Online (Sandbox Code Playgroud)

所以你只需将指针设置为第一条记录并从那里开始.它从java 1.2开始就可以使用,我只是想为ResultSet存在一个特定记录的人提这个.

  • 使用“first()”需要一个可滚动的结果集。如果结果集是“TYPE_FORWARD_ONLY”,API 要求抛出异常。 (2认同)

Pau*_*lin 6

您必须先执行result.next()才能访问结果.这是一个很常见的习语

ResultSet rs = stmt.executeQuery();
while (rs.next())
{
   int foo = rs.getInt(1);
   ...
}
Run Code Online (Sandbox Code Playgroud)