• 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);
    

      

  • 相关阅读:
    matplotlib直方图学习小记
    matplotlib饼状图学习小记
    P2306 被yyh虐的mzc
    P1776 宝物筛选_NOI导刊2010提高(02)&& 多重背包二进制优化
    51NOD 1445 变色DNA
    51NOD 1459 迷宫游戏
    CODEVS 1001 舒适的路线
    P4514 上帝造题的七分钟
    1082 线段树练习 3 && 树状数组区间修改区间查询
    P4145 上帝造题的七分钟2 / 花神游历各国
  • 原文地址:https://www.cnblogs.com/Bernard94/p/15771347.html
Copyright © 2020-2023  润新知