java:使用executeQuery(string)方法不支持错误?

phi*_*ill 5 java sql-server

我正在做一个简单的preparestatement查询执行,并且它抛出了这个错误:java.sql.SQLException:net.sourceforge.jtds.jdbc.JtdsPreparedStatement.notSupported在这种类型的语句中不支持使用executeQuery(string)方法(JtdsPreparedStatement.java:197)在testconn.itemcheck(testconn.java:58)的net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:822)

我有什么不正确的想法吗?在此先感谢这里是代码:

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 
Run Code Online (Sandbox Code Playgroud)

Vin*_*lds 6

有几件事值得检查:

  1. 使用其他别名.使用COUNT作为别名会遇到麻烦.
  2. 查询对象不需要传递两次,一次是在语句准备期间以及稍后执行期间.在con.prepareStatement(query);ie语句准备中使用它就足够了.

附录

令人怀疑的是,jTDS支持对PreparedStatement使用String arg方法.原理是PreparedStatement.executeQuery()似乎已实现,而Statement.executeQuery(String)似乎已在PreparedStatement.executeQuery()中被覆盖以抛出声明的异常.


Dre*_*lls 6

所以...

PreparedStatement pstmt = con.prepareStatement(query); 
pstmt.setString(1,itemid);
java.sql.ResultSet rs = pstmt.executeQuery(query);
Run Code Online (Sandbox Code Playgroud)

不像Statement,与PreparedStatement你通过查询SQL当你创建(通过Connection对象).你正在这样做,但是当你打电话的时候,你也会再次传递它executeQuery(query).

使用为PreparedStatement定义的executeQuery()无参数重载.

所以...

PreparedStatement pstmt = con.prepareStatement(query); 
pstmt.setString(1,itemid);
java.sql.ResultSet rs = pstmt.executeQuery();
Run Code Online (Sandbox Code Playgroud)