Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with PreparedStatement

 
Rahul Dasgupta
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
My java program compiled but throws an exception.
Can you tell me why this is happening?
Thanks for any help
Rahul
DBaccess.java
import java.sql.*;
import java.io.*;
public class DBaccess
{
public static void main(String args[])
{
ResultSet res;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc dbc:nw");
PreparedStatement ps = con.prepareStatement(
"Select * from Products where ProductID = ? " );
BufferedReader in = new BufferedReader(
new InputStreamReader( System.in ) );
System.out.print( "Enter Product ID : ");
ps.setString( 1, in.readLine( ) );
System.out.println( "Read");
res = ps.executeQuery( );
System.out.println("Executed!");
System.out.println( "Name Is : " + res.getString( 6 ) );
}
catch(Exception e)
{
System.out.println("Some exception has occured in DBaccess");
e.printStackTrace();
}
}
}
Error Message -
Enter Product ID : 4
Read
Executed!
Some exception has occured in DBaccess
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid cursor state
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6106)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:6263)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(JdbcOdbc.java:3307)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(JdbcOdbcResultSet.java:
5492)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:342)
at DBaccess.main(DBaccess.java:20)
PS. I am working with Northwind sample database (Access) on Win XP.
Fields in Products table are:
ProductID AutoNumber
ProductName Text
SupplierID Number
CategoryID Number
QuantityPerUnit Text
UnitPrice Currency
UnitsInStock Number
UnitsOnOrder Number
ReorderLevel Number
Discontinued Yes/No
[ December 12, 2002: Message edited by: Rahul Dasgupta ]
[ December 12, 2002: Message edited by: Rahul Dasgupta ]
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to JDBC...
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to call res.next() to position the ResultSet cursor on the first row, before you can access any values from that row. I know that seems strange when you've only got one row - but it makes more sense as part of the standard idiom for processing multiple rows:
 
Rahul Dasgupta
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Working fine now,
Thanks.
- Rahul
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic