2010-01-22 42 views
46

我无法从ResultSet对象获取数据。这里是我的代码: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) 

什么我错在这里做什么?

回答

117

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

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

在if语句或循环中这很常见。

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

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

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

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

1

您需要将指针移动到第一行,要求数据之前:

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

如果创建拥有所有的查询方法(含),在不同的包中的类这是更好的,所以不是在每个班级中输入所有进程,您只需调用该班级的方法即可。

5

每个答案都使用.next()或使用.beforeFirst()和.next()。但为什么不是这样的:

result.first(); 

所以你只要设置指针到第一个记录,并从那里去。它从java 1.2开始就可用了,我只是想提一提ResultSet存在一个特定记录的人。

相关问题