PreparedStatement 使用like
在使用PreparedStatement進(jìn)行模糊查詢的時(shí)候廢了一番周折,以前一直都沒有注意這個(gè)問題。一般情況下我們進(jìn)行精確查詢,sql語句類似:select * from table where name =?,然后調(diào)用 PreparedStatement的setString等方法給?指定值。那么模糊查詢的時(shí)候應(yīng)該怎么寫呢?我首先嘗試了:select * from customer where name like ‘%?%’。
此時(shí)程序報(bào)錯(cuò),因?yàn)??被包含在了單引?hào)中,PreparedStatement并不視它為一個(gè)參數(shù)。后來上網(wǎng)查了相關(guān)的一些資料,發(fā)現(xiàn)可以這樣寫select * from table where name like ?;但是在指定參數(shù)的時(shí)候把?指定為”%”+name+”%”,name是指定的查詢條件。這樣就OK了。
一般情況下,我總是潛意識(shí)的認(rèn)定了?就是取代所指定的參數(shù),但是實(shí)際上我們可以對(duì)指定的參數(shù)進(jìn)行了一定的包裝之后再傳給?,比如這里我們?cè)趨?shù)的前后都加了一個(gè)%,然后再傳給?
String expr = "select * from table where url like ?";
pstmt = con.prepareStatement(expr);
String a="a";
pstmt.setString(1, "%"+a+"%");//自動(dòng)添加單引號(hào) (包裝后的參數(shù))
pstmt.execute();
System.out.println(pstmt.toString());//打印sql
//會(huì)默認(rèn)生成sql: select * from table where url like '%http%'