Statement與PreparedStatement的區別
原創 2014年04月18日 10:43:11java
1:建立時的區別: mysql
Statement statement = conn.createStatement();
PreparedStatement preStatement = conn.prepareStatement(sql);
執行的時候:
ResultSet rSet = statement.executeQuery(sql);
ResultSet pSet = preStatement.executeQuery();sql
由上能夠看出,PreparedStatement有預編譯的過程,已經綁定sql,以後不管執行多少遍,都不會再去進行編譯,數據庫
而 statement 不一樣,若是執行多變,則相應的就要編譯多少遍sql,因此從這點看,preStatement 的效率會比 Statement要高一些安全
[java] view plain copyapp
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.Statement;
-
- public class JDBCTest {
-
- public static void main(String[] args) throws Exception {
- //1 加載數據庫驅動
- Class.forName("com.mysql.jdbc.Driver");
-
- //2 獲取數據庫鏈接
- String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8";
- String user = "root";
- String password = "root";
- Connection conn = DriverManager.getConnection(url, user, password);
-
- //3 建立一個Statement
- String sql = "select id,loginName,email from user where id=";
- String tempSql;
- int count = 1000;
- long time = System.currentTimeMillis();
- for(int i=0 ;i<count ;i++){
- Statement statement = conn.createStatement();
- tempSql=sql+(int) (Math.random() * 100);
- ResultSet rSet = statement.executeQuery(tempSql);
- statement.close();
- }
- System.out.println("statement cost:" + (System.currentTimeMillis() - time));
-
- String psql = "select id,loginName,email from user where id=?";
- time = System.currentTimeMillis();
- for (int i = 0; i < count; i++) {
- int id=(int) (Math.random() * 100);
- PreparedStatement preStatement = conn.prepareStatement(psql);
- preStatement.setLong(1, new Long(id));
- ResultSet pSet = preStatement.executeQuery();
- preStatement.close();
- }
- System.out.println("preStatement cost:" + (System.currentTimeMillis() - time));
- conn.close();
- }
-
- }
上述代碼反覆執行,dom
statement cost:95 preStatement cost:90測試
statement cost:100 preStatement cost:89url
statement cost:92 preStatement cost:86spa
固然,這個也會跟數據庫的支持有關係,http://lucaslee.iteye.com/blog/49292 這篇帖子有說明
雖然沒有更詳細的測試 各類數據庫, 可是就數據庫發展 版本越高,數據庫對 preStatement的支持會愈來愈好,
因此整體而言, 驗證 preStatement 的效率 比 Statement 的效率高
2>安全性問題
這個就很少說了,preStatement是預編譯的,因此能夠有效的防止 SQL注入等問題
因此 preStatement 的安全性 比 Statement 高
3>代碼的可讀性 和 可維護性
這點也不用多說了,你看老代碼的時候 會深有體會
preStatement更勝一籌
別的暫時尚未想到,說沒有查到會更好一些(汗),若是有別的差別,之後再補充