就這牛客網的一道題,進行分析PreparedStatement與Statement的區別。
題目:
關於PreparedStatement與Statement描述錯誤的是()
A 一般而言,PreparedStatement比Statement執行效率更高
B PreparedStatement會預編譯SQL語句
C Statement每次都會解析/編譯SQL,確立並優化數據獲取路徑
D 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要高一些。
1 package test; 2 3 import java.sql.*; 4 5 /** 6 * @author zsh 7 * @company wlgzs 8 * @create 2019-03-21 20:19 9 * @Describe JDBCTest,PreparedStatement與Statement區別 10 */ 11 public class JDBCTest { 12 13 public static void t() throws ClassNotFoundException, SQLException { 14 //1 加載數據庫驅動 15 Class.forName("com.mysql.jdbc.Driver"); 16 //2 獲取數據庫連接 17 String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useSSL=false&characterEncoding=UTF-8"; 18 String user = "root" ; 19 String password = "root" ; 20 Connection conn = DriverManager.getConnection(url, user, password); 21 //3 創建一個Statement 22 String sql = "select * from user where id= " ; 23 String tempSql; 24 int count = 1000 ; 25 long time = System.currentTimeMillis(); 26 for ( int i= 0 ;i<count ;i++){ 27 Statement statement = conn.createStatement(); 28 tempSql=sql+(int ) (Math.random() * 100 ); 29 ResultSet rSet = statement.executeQuery(tempSql); 30 statement.close(); 31 } 32 System.out.println("statement cost:" + (System.currentTimeMillis() - time)); 33 34 String psql = "select * from user where id= ?" ; 35 time = System.currentTimeMillis(); 36 for ( int i = 0 ; i < count; i++) { 37 int id=( int ) (Math.random() * 100 ); 38 PreparedStatement preStatement = conn.prepareStatement(psql); 39 preStatement.setLong(1 , new Long(id)); 40 ResultSet pSet = preStatement.executeQuery(); 41 preStatement.close(); 42 } 43 System.out.println("preStatement cost:" + (System.currentTimeMillis() - time)); 44 conn.close(); 45 } 46 47 public static void main(String[] args) throws SQLException, ClassNotFoundException { 48 for (int i = 0; i < 4; i++) { 49 System.out.println("-------"+i+"------"); 50 t(); 51 } 52 } 53 }
運行結果:
雖然沒有更詳細的測試 各種數據庫, 但是就數據庫發展 版本越高,數據庫對 preStatement的支持會越來越好,所以總體而言, 驗證 preStatement 的效率 比 Statement 的效率高。
2、安全性問題
這個就不多說了,preStatement是預編譯的,所以可以有效的防止 SQL注入等問題。所以 preStatement 的安全性 比 Statement 高
3、代碼的可讀性 和 可維護性
這點也不用多說了,你看老代碼的時候 會深有體會