简体   繁体   中英

Error in SQL update query in JDBC

For the command given below, if the variable body_template contains " Abhinav's number", it shows the following error:

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 's number

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.

Kindly suggest how should I redesign my query so as to handle such cases. Note: Input can't be changed. The problem is coming due to the inclusion of ' in the input.

Note: Input can't be changed. The problem is coming due to the inclusion of ' in the input.

Best practice is to use PreparedStatement for binding the input values with the query parameters. It manages to escape special characters if any in the input values.

Example :

// 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.

if body_template doesn't contain ", then this code would work. obviously if body_template does have it then you run into same problem as before. just make sure body_template only contains one type of quotes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM