JDBC中Statement和PreparedStatement性能的比较

来源:互联网 发布:微信大屏幕霸屏源码 编辑:程序博客网 时间:2024/06/04 18:57

1.模拟测试的环境
(1)分别创建两个函数作为Statement和PreparedStatement测试方法
(2)分别向数据库插入10000条数据;
(3)比较Statement和PreparedStatement花费时间
测试如下:

    //利用Statement进行数据的添加    @SuppressWarnings("unused")    private static void test_Statement() throws Exception {        long start=System.currentTimeMillis();        Connection con=null;        Statement state=null;        try{            con=DBUtil.getConnection();            con.setAutoCommit(false);            state=con.createStatement();            for(int x=0;x<500000;x++){                String sql="insert into  user(name,password) values('"+"tim"+x+"',"+x+");";                int num=state.executeUpdate(sql);            }            }catch(Exception e){                con.rollback();                e.printStackTrace();            }            con.commit();            DBUtil.close(null, state, con);            System.out.println("总时间:"+(System.currentTimeMillis()-start));    }

//利用PreparedStatement进行数据的添加    @SuppressWarnings("unused")    private static void test_PreparedStatement() throws Exception {        long start=System.currentTimeMillis();        Connection con=null;        PreparedStatement ps=null;        try{            con=DBUtil.getConnection();            con.setAutoCommit(false);            String sql="insert into  user(name,password) values(?,?);";            ps=con.prepareStatement(sql);            for(int x=0;x<500000;x++){                ps.setString(1, "tim"+x);                ps.setInt(2, x);                ps.executeUpdate();            }        }catch(Exception e){                con.rollback();            e.printStackTrace();        }        con.commit();        DBUtil.close(null, ps, con);        System.out.println("总时间:"+(System.currentTimeMillis()-start));    }

时间对比:
Statement :
-| 100000 —消耗时间—>11034毫秒;
-| 200000 —消耗时间—>20654毫秒;
-| 500000 —消耗时间—>52206毫秒;
PreoaredStatement:
-| 100000 —消耗时间—>10411毫秒;
-| 200000 —消耗时间—>20836毫秒;
-| 500000 —消耗时间—>48999毫秒;
实验结果对比
随着数据的不断增大,PreparedStatement的效果是Statement
的效果要好。
在安全性上PreparedStatement会进行预处理编译,在数据的安全性上PreparedStatement是可以防止Statement的sql注入导致的漏洞问题

0 0
原创粉丝点击