Statement與PreparedStatement的區別

1:創建時的區別:

    Statement statement = conn.createStatement();
    PreparedStatement preStatement = conn.prepareStatement(sql);
    執行的時候:
    ResultSet rSet = statement.executeQuery(sql);
    ResultSet pSet = preStatement.executeQuery();

由上可以看出,PreparedStatement有預編譯的過程,已經綁定sql,之後無論執行多少遍,都不會再去進行編譯,

而 statement 不同,如果執行多變,則相應的就要編譯多少遍sql,所以從這點看,preStatement 的效率會比 Statement要高一些

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();
    }
    
}

上述代碼反覆執行,

statement cost:95           preStatement cost:90

statement cost:100         preStatement cost:89

statement cost:92           preStatement cost:86

當然,這個也會跟數據庫的支持有關係,http://lucaslee.iteye.com/blog/49292  這篇帖子有說明

雖然沒有更詳細的測試 各種數據庫, 但是就數據庫發展 版本越高,數據庫對 preStatement的支持會越來越好,

所以總體而言, 驗證  preStatement 的效率 比 Statement 的效率高

2>安全性問題

這個就不多說了,preStatement是預編譯的,所以可以有效的防止 SQL注入等問題

所以 preStatement 的安全性 比 Statement 高

3>代碼的可讀性 和 可維護性
這點也不用多說了,你看老代碼的時候  會深有體會

preStatement更勝一籌

別的暫時還沒有想到,說沒有查到會更好一些(汗),如果有別的差異,以後再補充



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章