ResultSet exception - before the start of the result set

I am having problems 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)); } 

Error tracing:

 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?

+45
java jdbc
Jan 22 '10 at 20:25
source share
6 answers

Basically, you position the cursor in front of the first row and then query the data. You need to move the cursor to the first line.

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

This is usually done in an if statement or in a loop.

 if(result.next()){ foundType = result.getString(1); } 
+113
Jan 22 '10 at 20:29
source share

Before accessing the result, you must do result.next (). This is a very common idiom to do.

 ResultSet rs = stmt.executeQuery(); while (rs.next()) { int foo = rs.getInt(1); ... } 
+6
Jan 22 '10 at 20:29
source share

Each answer uses .next () or uses .beforeFirst () and then .next (). But why not this:

 result.first(); 

So, you just pointed to the first entry and go from there. It is available with java 1.2, and I just wanted to mention this for those who have a ResultSet one specific record.

+4
Nov 30 '13 at 16:23
source share

It’s better if you create a class that has all the request methods, inclusive, in a different package, so instead of entering the whole process in each class, you simply call the method from this class.

+2
Sep 12 '13 at 23:08
source share

You need to call next() to start reading the values ​​from the first line. beforeFirst places the cursor on the first line, so there is no data to read.

+1
Jan 22 '10 at 20:30
source share

You need to move the pointer to the first line before requesting data:

 result.beforeFirst(); result.next(); String foundType = result.getString(1); 
+1
Jan 22
source share



All Articles