Java JDBC中的SQL更新查询出错

Java JDBC中的SQL更新查询出错,java,mysql,sql,string,jdbc,Java,Mysql,Sql,String,Jdbc,对于下面给出的命令,如果变量body_模板包含“Abhinav的编号”,则显示以下错误: 您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,了解使用near的编号的正确语法 String sql_command = "Update email_template set body_template='"+body_template+"' WHERE id="+idno; //body_template, idno are of type String stmt.execu

对于下面给出的命令,如果变量body_模板包含“Abhinav的编号”,则显示以下错误:

您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,了解使用near的编号的正确语法

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.
请建议我如何重新设计我的查询以便处理此类情况。注意:无法更改输入。问题的出现是因为输入中包含了'

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_模板不包含“,则此代码将起作用。显然,如果body_模板包含它,则会遇到与以前相同的问题。只需确保body_模板仅包含一种类型的引号

注意:无法更改输入。问题是由于输入中包含了“”

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, 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();

数据库中的
body\u模板
的数据类型是什么?因为问题是因为您的值中的
。body\u模板的类型是mediumtext查看我的答案了解解决方案使用
PreparedStatement
传递参数。除了修复语法错误外,它还将阻止SQL注入+1。快速检查-您愿意吗考虑将代码中的字符串替换为更改输入吗?我不太确定我的答案是否在约束条件下。为了处理SQL语法约束,我不喜欢手动替换输入字符串中的特定事件。API的PST已经为这个目的服务。