JDBC中的SQL更新查询出错

时间:2014-06-23 09:55:26

标签: java mysql sql string 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.

请建议我应该如何重新设计查询以处理此类情况。注意:输入无法更改。问题是由于在输入中包含'。

2 个答案:

答案 0 :(得分:2)

  

注意:输入无法更改。问题来自于包含'在输入中。

最佳做法是使用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();

答案 1 :(得分:0)

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只包含一种类型的引号

相关问题