Reputation: 3534
After getting results from a SQL query, I can access the results via a while loop :
String query = "SELECT TAX_RATE_ID FROM dbo.TAX_RATE where zip_code = 38401";
ResultSet rs= conn.createStatement().executeQuery(query);
while (rs.next()) {
System.out.println(rs.getString("TAX_RATE_ID"));
}
But I don't want to access them in a while loop, I want to just get the single result and return the value, since I know what to expect when the query is ran. So I tried this:
String query = "SELECT TAX_RATE_ID FROM dbo.TAX_RATE where zip_code = 38401";
ResultSet rs= conn.createStatement().executeQuery(query);
rs.first();
System.out.println(rs.getString("TAX_RATE_ID"));
But I get this error:
Exception in thread "main" java.sql.SQLException: ResultSet may only be accessed in a forward direction.
at net.sourceforge.jtds.jdbc.JtdsResultSet.checkScrollable(JtdsResultSet.java:319)
at net.sourceforge.jtds.jdbc.JtdsResultSet.first(JtdsResultSet.java:545)
at com.kirklands.automation.ecom.Testing.main(Testing.java:12)
Upvotes: 0
Views: 3172
Reputation:
You don't have to call next()
in a loop. If you just want to get the first row, use:
String query = "SELECT TAX_RATE_ID FROM dbo.TAX_RATE where zip_code = 38401";
ResultSet rs= conn.createStatement().executeQuery(query);
if (rs.next()) {
System.out.println(rs.getString("TAX_RATE_ID"));
}
Unrelated, but:
conn.createStatement().executeQuery()
will create a Statement
instance that you can't clean up properly using close()
.
Upvotes: 2