views:

52

answers:

2

I'm doing a simple preparedstatement query execution and its throwing me this error: java.sql.SQLException: Use of the executeQuery(string) method is not supported on this type of statement at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.notSupported(JtdsPreparedStatement.java:197) at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:822) at testconn.itemcheck(testconn.java:58)

Any ideas what i'm doing incorrectly? thanks in advance here is the code:

private static int itemcheck (String itemid ) { 
  String query;
  int count = 0;
  try { 
   Class.forName("net.sourceforge.jtds.jdbc.Driver");
        con = java.sql.DriverManager.getConnection(getConnectionUrl2());
   con.setAutoCommit(false);
   query = "select count(*) as itemcount from timitem where itemid like ?";

   //PreparedStatement pstmt = con.prepareStatement(query); 
   //pstmt.executeUpdate(); 

   PreparedStatement pstmt = con.prepareStatement(query);
   pstmt.setString(1,itemid);
   java.sql.ResultSet rs = pstmt.executeQuery();



   while (rs.next()) {
     count = rs.getInt(1);
    System.out.println(count);
   } //end while 



  }catch(Exception e){ e.printStackTrace(); } 

  return (count);

} //end itemcheck 
+2  A: 

A couple of things are worth checking:

  1. Use a different alias. Using COUNT as an alias would be asking for trouble.
  2. The query object need not be passed twice, once during preparation of the statement and later during execution. Using it in con.prepareStatement(query); i.e. statement preparation, is enough.

ADDENDUM

It's doubtful that jTDS supports usage of the String arg method for PreparedStatement. The rationale is that PreparedStatement.executeQuery() appears to be implemented, whereas Statement.executeQuery(String) appears to have been overriden in PreparedStatement.executeQuery() to throw the stated exception.

Vineet Reynolds
A: 

So...

PreparedStatement pstmt = con.prepareStatement(query); 
pstmt.setString(1,itemid);
java.sql.ResultSet rs = pstmt.executeQuery(query);

Unlike Statement, with PreparedStatement you pass the query sql when you create it (via the Connection object). You're doing it, but then you're also passing it again, when you call executeQuery(query).

Use the no-arg overload of executeQuery() defined for PreparedStatement.

So...

PreparedStatement pstmt = con.prepareStatement(query); 
pstmt.setString(1,itemid);
java.sql.ResultSet rs = pstmt.executeQuery();
Drew Wills