- 介紹
在Ibatis中我們使用SqlMap進行Sql查詢時需要引用參數,在參數引用中遇到的符號#和$之間的區分為,#可以進行與編譯,進行類型匹配,而$不進行數據類型匹配,例如:
select * from table where id = #id# ,其中如果字段id為字符型,那么#id#表示的就是'id'類型,如果id為整型,那么#id#就是id型。select * from table where id = $id$ ,如果字段id為整型,Sql語句就不會出錯,但是如果字段id為字符型,那么Sql語句應該寫成 select * from table where id = '$id$'。
- 區別
$ 的作用實際上是字符串拼接:
1 select * from $tableName$
等效於:
1 StringBuffer sb = new StringBuffer(256); 2 sb.append("select * from ").append(tableName); 3 sb.toString();
#用於變量替換
1 select * from table where id = #id#
等效於:
1 prepareStement = stmt.createPrepareStement("select * from table where id = ?") ; 2 prepareStement.setString(1,'abc');
- 用法總結
1、對於變量部分, 應當使用#,這樣可以有效的防止sql注入,並且# 都是用到了prepareStement,這樣對效率也有一定的提升。
2、$只是簡單的字符拼接而已,對於非變量部分, 那只能使用$, 實際上, 在很多場合,$也是有很多實際意義的 。
例如 :select * from $tableName$ 對於不同的表執行統一的查詢。 $只是字符串拼接, 所以要特別小心sql注入問題。
3、能同時使用#和$的時候最好用#。
