Java学习之Sql语句中包含单引号进行转换。

业务场景:

某个需求开发中需要更新数据库中的字段,但是字段中包含特殊字段:单引号('),然后与Sql语句冲突。

新建数据库"people"(字段:id、name、status、content)

新增数据:1、zhangsan、1、'测试'。

 

 

需求:需要把content字段中的('测试') 改为('hello') 

注意:目的要改成:'hello',不是:hello

问题:

此时单纯写Sql或者在系统中更新'content'字段会报错:

update people set content = ''hello'' where id = 1;

Error Code: 1064. 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 'hello'' where id = 1' at line 1

String content = "'hello'";
String sql = "update people set content = '"+content +"' where id = 1";
service.excuteSql(sql );

   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 'hello'' where id = 1' at line 1。

解决办法:

用两个单引号代替一个单引号(注意:两个单引号,不是双引号!)

update people set content = '''hello''' where id = 1;

 

        String content = "'hello'";
        if (content.contains("'")) {
            content.replace("'", "\'\'");
        }
        String sql = "update people set content = '" + content + "' where id = 1";
        service.excuteSql(sql);

  

posted @ 2022-01-06 15:34  请别耽误我写BUG  阅读(536)  评论(0编辑  收藏  举报