JDBC中Statement和PreparedStatement性能的比较

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值