1.增長SQL代碼可讀性sql
2.佔位符能夠預先編譯,提升執行效率this
3.防止SQL注入spa
4.用佔位符的目的是綁定變量,這樣能夠減小數據SQL的硬解析,因此執行效率會提升很多code
假設要將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");blog
使用綁定變量:
UPDATE employees SET salay = ? WHERE id = ?"get
兩者區別在於,不用綁定變量,則至關於反覆解析、執行了1w個sql語句。使用綁定變量,解析sql語句只用了一次,以後的9999次複用第一次生成的執行計劃。顯然,後者效率會更高一些。編譯
主要是Model類查詢方法find和分頁查詢方法paginate、Db類update、batch等方法中使用class
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);