2010-08-05 82 views
5

我正在做一個簡單的準備語句查詢執行,它拋出了這個錯誤: java.sql.SQLException:net.sourceforge.jtds.jdbc上的這種類型的語句不支持使用executeQuery(string)方法。 JtdsPreparedStatement.notSupported(JtdsPreparedStatement.java:197)在net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:822)在testconn.itemcheck(testconn.java:58)java:使用executeQuery(string)方法不支持錯誤?

任何想法就是我做錯了嗎?在此先感謝 這裏是代碼:

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 

回答

5

幾件事情是值得的檢查:

  1. 使用不同的別名。使用COUNT作爲別名會造成麻煩。
  2. 查詢對象不需要傳遞兩次,一次在語句準備期間和稍後在執行期間傳遞。在con.prepareStatement(query);即使用語句準備中使用它就足夠了。

附錄

這是值得懷疑的JTDS支持預處理字符串ARG方法的使用。基本原理是PreparedStatement.executeQuery()似乎已經實現,而Statement.executeQuery(String)似乎已經在PreparedStatement.executeQuery()中被重寫以拋出聲明的異常。

+0

對於第二點......即使我做了同樣的錯誤。謝謝你節省了我很多時間 – 2015-01-05 11:19:19

5

所以......

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

不像Statement,與PreparedStatement您通過在創建它(通過Connection對象)查詢SQL。你正在這樣做,但是當你打電話給executeQuery(query)時,你也會再次通過。

使用爲PreparedStatement定義的no-arg overload of executeQuery()

所以......

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