JDBC批处理操作

使用Statement接口进入操作

多条SQL 语句批处理,调用executeBatch()方法执行

使用currentTimeMillis()方法计算消耗的时间,最后使用commit()方法提交业务

 

public class Demo{
    public static void main(String[] args) {
    //初始化连接对象和接口对象,方便下面捕获异常
        Connection connection = null;
        Statement statement = null;
        ResultSet rs = null;
        try {
        //加载数据库驱动
            Class.forName("com.mysql.jdbc.Driver");
        //建立连接
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_test", "root", "123456");
            long start = System.currentTimeMillis();
            connection.setAutoCommit(false);        //设置为手动提交
            statement = connection.createStatement();   //使用连接对象创建对象
            //调用addBatch()插入100条数据
            for (int i = 0; i < 100; i++) {
                statement.addBatch("insert into user (name,password,regTime)values ('demo" + i + "','1234567890',now())");
            }
            statement.executeBatch();
            connection.commit();        //提交事务
            long end = System.currentTimeMillis();
            System.out.println("插入100条数据,用时为: " + (end - start)+"毫秒");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (statement != null) {
                    statement.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值