• MyBatis中#{}和${}的区别详解



    1、#将传入的数据当成一个字符串,会对自动传入的数据加一个双引号。例如

    order by #id#,如果传入的值是111,那么解析成sql时的值变为order by "111",如果传入的值是id,在解析成sql为order by "id"

    其实原sql语句通常写成 order by #{id} 与order by #id#的效果一样

    2、$将传入的数据直接显示在sql语句中。例如 order by ${id},如果传入的值是9则解析成sql语句为order by 9


    3、#方式能够很大程度上防止sql注入,而$无法防止sql的注入,

      $一般用于传入数据库对象,例如传入表名

     一般能用#就别用$

    mybatis排序时使用order by动态参数时需要住哟,使用$而不是#

    =================================

    1. #将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。如:order by #user_id#,如果传入的值是111,那么解析成sql时的值为order by "111", 如果传入的值是id,则解析成的sql为order by "id".

    2. $将传入的数据直接显示生成在sql中。如:order by $user_id$,如果传入的值是111,那么解析成sql时的值为order by user_id, 如果传入的值是id,则解析成的sql为order by id.

    3. #方式能够很大程度防止sql注入。 

    4.$方式无法防止Sql注入。

    5.$方式一般用于传入数据库对象,例如传入表名.

    6.一般能用#的就别用$.

    MyBatis排序时使用order by 动态参数时需要注意,用$而不是#

    字符串替换

    默认情况下,使用#{}格式的语法会导致MyBatis创建预处理语句属性并以它为背景设置安全的值(比如?)。这样做很安全,很迅速也是首选做法,有时你只是想直接在SQL语句中插入一个不改变的字符串。比如,像ORDER BY,你可以这样来使用:
    ORDER BY ${columnName}

    这里MyBatis不会修改或转义字符串。

    重要:接受从用户输出的内容并提供给语句中不变的字符串,这样做是不安全的。这会导致潜在的SQL注入攻击,因此你不应该允许用户输入这些字段,或者通常自行转义并检查。

    mybatis本身的说明:

    String Substitution
    By default, using the #{} syntax will cause MyBatis to generate PreparedStatement properties and set the values safely against the PreparedStatement parameters (e.g. ?). While this is safer, faster and almost always preferred, sometimes you just want to directly inject a string unmodified into the SQL Statement. For example, for ORDER BY, you might use something like this:
    ORDER BY ${columnName}
    Here MyBatis won't modify or escape the string.
    NOTE It's not safe to accept input from a user and supply it to a statement unmodified in this way. This leads to potential SQL Injection attacks and therefore you should either disallow user input in these fields, or always perform your own escapes and checks.


    1. 使用#{}格式的语法在mybatis中使用Preparement语句来安全的设置值,执行sql类似下面的:


    PreparedStatement ps = conn.prepareStatement(sql);
    ps.setInt(1,id);

    这样做的好处是:更安全,更迅速,通常也是首选做法。

    2. 不过有时你只是想直接在 SQL 语句中插入一个不改变的字符串。比如,像 ORDER BY,你可以这样来使用:

    ORDER BY ${columnName}

    此时MyBatis 不会修改或转义字符串。

    这种方式类似于:

    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery(sql);

    ————————————————
    版权声明:本文为CSDN博主「xlj3」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/luman1991/article/details/52623184

  • 相关阅读:
    jython resources
    Installing a Library of Jython ScriptsPart of the WebSphere Application Server v7.x Administration Series Series
    jython好资料
    ulipad install on 64bit win7 has issue
    an oracle article in high level to descibe how to archtichre operator JAVA relevet project
    table的宽度,单元格内换行问题
    Linux常用命令大全
    dedecms系统后台登陆提示用户名密码不存在
    登录织梦后台提示用户名不存在的解决方法介绍
    Shell常用命令整理
  • 原文地址:https://www.cnblogs.com/muxi0407/p/11607583.html
Copyright © 2020-2023  润新知