ResultSetexception – 在结果集开始之前

我无法从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) 

我在这里做错了什么?

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

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

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

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

您必须先执行result.next(),然后才能访问结果。 这是一个非常常见的习惯用法

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

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

 result.first(); 

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

最好是创build一个包含所有查询方法的类(包含在不同的包中),所以不要在每个类中键入所有进程,而只需调用该类的方法。

您必须先调用next()然后才能开始读取第一行的值。 beforeFirst将光标放在第一行之前 ,所以没有数据要读取。

在请求数据之前,您需要将指针移至第一行:

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