[英]Error in SQL update query in JDBC
對於以下給出的命令,如果變量body_template包含“ Abhinav的數字”,則顯示以下錯誤:
您的SQL語法有誤; 查看與您的MySQL服務器版本相對應的手冊,以獲取在的數字附近使用的正確語法
String sql_command = "Update email_template set body_template='"+body_template+"' WHERE id="+idno;
//body_template, idno are of type String
stmt.executeUpdate(sql_command); //Here stmt is a variable of type statement.
請提出我應該如何重新設計查詢以處理此類情況。 注意:輸入不能更改。 由於輸入中包含“”,因此出現了問題。
注意:輸入不能更改。 由於輸入中包含“”,因此出現了問題。
最佳實踐是使用PreparedStatement
將輸入值與查詢參數綁定。 如果輸入值中有特殊字符,它將設法轉義。
范例 :
// body_template, idno are of type String
String sql_command = "Update email_template set body_template=? WHERE id=?";
PreparedStatement pst = con.prepareStatement( sql_command );
pst.setString( 1, body_template );
pst.setString( 2, idno );
int updateResult = pst.executeUpdate();
String sql_command = "Update email_template set body_template=\""+body_template+"\" WHERE id="+idno;
//body_template, idno are of type String
stmt.executeUpdate(sql_command); //Here stmt is a variable of type statement.
如果body_template不包含“,那么此代碼將起作用。顯然,如果body_template包含它,那么您將遇到與以前相同的問題。只需確保body_template僅包含一種引號
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.