Java com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException with PreparedStatement
我在DAO类中有以下代码:Java com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException with PreparedStatement,java,mysql,jdbc,Java,Mysql,Jdbc,我在DAO类中有以下代码: public boolean employeeExists(String employeeCode) throws InstantiationException, SQLException { String SQL_TEXT = "select count(*) from employee where emp_code=?;"; int scalarValue = 0; Connection conn = DatabaseAccess.ge
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 workbench中执行,但正在使用JDBC引发异常。
这是mysql jdbc驱动程序中的某种错误吗?请提供帮助。您已经使用包含查询(SQL\u TEXT)的参数创建了
PreparedStatement
,无需再次调用它
ResultSet rs = pstmt.executeQuery(SQL_TEXT);
执行此操作时,您正在执行SQL\u TEXT
,而没有将变量设置为?
,因此您的查询包含一个MySql无法识别的询问标记。你只需要做:
ResultSet rs = pstmt.executeQuery();
因为您在中设置了SQL\u文本
PreparedStatement pstmt = conn.prepareStatement(SQL_TEXT);
您的问题在于:-
ResultSet rs=pstmt.executeQuery(SQL\u TEXT)代码>
将其更改为:-ResultSet rs=pstmt.executeQuery()代码>