就這牛客網的一道題,進行分析PreparedStatement與Statement的區別。java
Statement statement = conn.createStatement();
PreparedStatement preStatement = conn.prepareStatement(sql);
執行的時候: mysql
ResultSet rSet = statement.executeQuery(sql);
ResultSet pSet = preStatement.executeQuery();
由上能夠看出,PreparedStatement有預編譯的過程,已經綁定sql,以後不管執行多少遍,都不會再去進行編譯,而 statement 不一樣,若是執行多變,則相應的就要編譯多少遍sql,因此從這點看,preStatement 的效率會比 Statement要高一些。sql
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 的效率高。安全
二、安全性問題dom
這個就很少說了,preStatement是預編譯的,因此能夠有效的防止 SQL注入等問題。因此 preStatement 的安全性 比 Statement 高測試
三、代碼的可讀性 和 可維護性
這點也不用多說了,你看老代碼的時候 會深有體會優化