You need to move the cursor though the ResultSet
with next()
ResultSet rset = s.executeQuery("SELECT * FROM product");
if (rset.next()) {
System.out.println(rset.getString("title"));
}
Domanda
I am using BlueJ to carry out some tasks is Java. I can not understand why I can't get any records from my MS Access database. Any help will be appreciated
import java.sql.*;
public class Database
{
private Statement s;
/**
* Constructor for objects of class database
*/
public database()
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}catch(ClassNotFoundException exp){
System.err.println(exp);
}
try{
Connection con = DriverManager.getConnection("jdbc:odbc:POS", "", "");
this.s = con.createStatement();
}catch(SQLException e){
e.printStackTrace();
}
}
public void test(){
try{
this.s.executeQuery("SELECT * FROM product");
ResultSet rset = s.getResultSet();
System.out.println(rset.getString("title"));
}catch(SQLException e){
e.printStackTrace();
}
}
}
Here is the output I get when running test() function
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid cursor state at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6956) at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113) at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(JdbcOdbc.java:3906) at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(JdbcOdbcResultSet.java:5697) at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:353) at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:410) at database.test(database.java:35) at _SHELL9.run(_SHELL9.java:8) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at bluej.runtime.ExecServer$3.run(ExecServer.java:725)
I have the ODBC driver set up and my database name is right. It is not password protected.
Thank you in advance
Soluzione
You need to move the cursor though the ResultSet
with next()
ResultSet rset = s.executeQuery("SELECT * FROM product");
if (rset.next()) {
System.out.println(rset.getString("title"));
}
Altri suggerimenti
A ResultSet
is a set, so you have to iterate
over it:
ResultSet rset = s.executeQuery("SELECT * FROM product");
while(rset.next()){
System.out.println(rset.getString("title"));
}
P.S. don't forget to close the ResultSet
and Statement
when you are done with them.