Jfinal數據庫操作語句中占位符的使用


占位符的優點:

1.增加SQL代碼可讀性

2.占位符可以預先編譯,提高執行效率

3.防止SQL注入

4.用占位符的目的是綁定變量,這樣可以減少數據SQL的硬解析,所以執行效率會提高不少

假設要將id從1到10000的員工的工資都更新為150.00元,
不使用綁定變量:
sql.executeQuery("UPDATE employees SET salay = 150.00 WHERE id = 1");
sql.executeQuery("UPDATE employees SET salay = 150.00 WHERE id = 2");
sql.executeQuery("UPDATE employees SET salay = 150.00 WHERE id = 3");
sql.executeQuery("UPDATE employees SET salay = 150.00 WHERE id = 4");
....
sql.executeQuery("UPDATE employees SET salay = 150.00 WHERE id = 10000");

使用綁定變量:
UPDATE employees SET salay = ? WHERE id = ?"

二者區別在於,不用綁定變量,則相當於反復解析、執行了1w個sql語句。使用綁定變量,解析sql語句只用了一次,之后的9999次復用第一次生成的執行計划。顯然,后者效率會更高一些。

Jfinal中的占位符:

主要是Model類查詢方法find和分頁查詢方法paginate、Db類update、batch等方法中使用

1. 查詢參數無需添加通配符比如%、_等,可以直接使用

1 String userId = this.getPara("userId");
2 User.dao.find("select * from t_er_user where userId = ?", userId);

2. 該參數需要添加通配符

1 String userName = this.getPara("userName");
2 Object [] para = new Object[]{"%" + userName + "%"};
3 User.dao.find("select * from t_er_user where userName like ?", para);

3. 多個參數,其中有參數需要添加通配符

1 String userId = this.getPara("userId");
2 String userName = this.getPara("userName");
3 Object [] para = new Object[]{userId, "%" + userName + "%"};
4 User.dao.find("select * from t_er_user where userId = ? and userName like ?", para);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM