PreparedStatement与Statement区别

  就这牛客网的一道题,进行分析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、代码的可读性 和 可维护性 
  这点也不用多说了,你看老代码的时候  会深有体会

posted @ 2019-03-21 20:33  张顺海  阅读(2398)  评论(0编辑  收藏  举报