preparedStatement SQL错误

时间:2014-01-20 11:32:57

标签: java mysql jdbc prepared-statement

这是我的代码:

public int checklogin(String email, String key){
int res = -1;
try
{
    String selectSQL = "SELECT id FROM table WHERE email = ? AND key = ?";
    PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
    preparedStatement.setString(1, email);
    preparedStatement.setString(2, key);

    ResultSet rs = preparedStatement.executeQuery();
    if (rs.next()) 
        res = rs.getInt("id");

    rs.close();   
    preparedStatement.close();          
} catch (Exception e) { e.printStackTrace(); }

return res;
}

但我明白了:

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 'key = 'AAA'' at line 1

问题出在哪里?

1 个答案:

答案 0 :(得分:2)

KEY是MySQL中的reserved word。它需要被转义

String selectSQL = "SELECT id FROM table WHERE email = ? AND `key` = ?";

在命名列名时,避免使用保留关键字始终是最佳解决方案。