2014-01-20 45 views
2

這裏是我的代碼:preparedStatement時SQL錯誤

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 

問題出在哪裏?

+0

看起來很好。嘗試在查詢瀏覽器中自行運行SQL語句。那樣有用嗎? –

+0

順便說一句,你應該在'finally'塊中執行close()語句,儘管這不會成爲問題的原因。 –

+0

您傳遞的電子郵件和密鑰的價值是什麼 - 是的,它們是字符串,但是它們中是否有特殊字符會導致編碼問題?像蒂姆B說的 - 它看起來不錯! –

回答

2

KEY是MySQL中的reserved word。它需要被轉義

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

命名列名時避免保留關鍵字總是最好的解決方案。

+0

它的工作原理。愚蠢的錯誤。 謝謝 – Alvins