Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (6.1k points)

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? 

1 Answer

0 votes
by (12.7k points)
edited by

Every answer uses .next() or uses .beforeFirst() and then .next(). But why cannot this:

result.first();

So you need to just set the pointer to the first record and go from there. It's possible since Java 1.2 and I just wanted to mention this for anyone whose ResultSet exists of one specific record. 

Want to be a SQL expert? Come and join this SQL training and certification program by Intellipaat.

Do check out the video below

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 9, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

Browse Categories

...