2015-10-26 57 views
0

我在DAO類下面的代碼:com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException與PreparedStatement的

public boolean employeeExists(String employeeCode) throws InstantiationException, SQLException { 
    String SQL_TEXT = "select count(*) from employee where emp_code=?;"; 

    int scalarValue = 0; 

    Connection conn = DatabaseAccess.getConnection(); 
    PreparedStatement pstmt = conn.prepareStatement(SQL_TEXT); 
    pstmt.setString(1, employeeCode); 

    try { 
     ResultSet rs = pstmt.executeQuery(SQL_TEXT); 
     if (rs.next()) { 
      scalarValue = rs.getInt(1); 
     } 
    } catch (SQLException e) { 
     // TODO: log error. 
     throw e; 
    } finally { 
     if (pstmt != null && !pstmt.isClosed()) 
      pstmt.close(); 
     if (conn != null && !conn.isClosed()) 
      conn.close(); 
    } 
    return scalarValue > 0; 
} 

當我運行的代碼,即調用DAO以上方法,我得到以下錯誤:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' 

語法看起來不錯,在mysql工作臺中執行,但使用JDBC拋出異常。 它是在MySQL jdbc驅動程序中的某種錯誤?請幫忙。

回答

0

你的問題是: - ResultSet rs = pstmt.executeQuery(SQL_TEXT);

將其更改爲: - ResultSet rs = pstmt.executeQuery();

0

您已經使用包含查詢的參數(SQL_TEXT)創建了PreparedStatement,您不需要再次調用它。

ResultSet rs = pstmt.executeQuery(SQL_TEXT); 

執行此操作時,您正在執行的SQL_TEXT無變量設置爲?,使您的查詢包含問號,那就是不被MySQL識別。你只需要做:

ResultSet rs = pstmt.executeQuery(); 

因爲你設置的SQL_TEXT

PreparedStatement pstmt = conn.prepareStatement(SQL_TEXT); 
相關問題