PreparedStatement与Statement效率的测试比较

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更胜一筹

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值