I'm having trouble 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)); }
The error trace:
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?
Once the connection is closed you can no longer use any of the resources (statements, prepared statements, result sets), all of them are automatically closed.
The JDBC ResultSet doesn't provide any isEmpty(), length() or size() method to check if its empty or not. Hence, when a Java programmer needs to determine if ResultSet is empty or not, it just calls the next() method and if next() returns false it means ResultSet is empty.
No matter how many rows are returned(starting from 0), the resultSet will never be null. The only case in which a resultset will remain null is when an exception is thrown... but the program flow will jump to the Exception handling block anyways.
In the mean time many result sets might opened and left unclosed. If it happens on a single database by multiple applications, the data updation is not perfect and may violate ACID properties rule for data presuming.
Basically you are positioning the cursor before the first row and then requesting data. You need to move the cursor to the first row.
result.next(); String foundType = result.getString(1);
It is common to do this in an if statement or loop.
if(result.next()){ foundType = result.getString(1); }
Every answer uses .next()
or uses .beforeFirst()
and then .next()
. But why not this:
result.first();
So You just set the pointer to the first record and go from there. It's available since java 1.2 and I just wanted to mention this for anyone whose ResultSet
exists of one specific record.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With