Statement与PreparedStatement的区别

来源:互联网 发布:潍坊网站推广优化 编辑:程序博客网 时间:2024/06/05 02:35

原文地址:http://blog.csdn.net/haorengoodman/article/details/23995347

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

当然,这个也会跟数据库的支持有关系

虽然没有更详细的测试各种数据库, 但是就数据库发展版本越高,数据库对preStatement的支持会越来越好,

所以总体而言, 验证preStatement的效率比Statement 的效率高

2>安全性问题

这个就不多说了,preStatement是预编译的,所以可以有效的防止SQL注入等问题

所以 preStatement 的安全性 比 Statement 高

3>代码的可读性 和 可维护性 
这点也不用多说了,你看老代码的时候  会深有体会

preStatement更胜一筹

别的暂时还没有想到,说没有查到会更好一些(汗),如果有别的差异,以后再补充



0 0
原创粉丝点击