MyBatis中#{}和${}的區別詳解

https://blog.csdn.net/luman1991/article/details/52623184

 

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章