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();
            }
        }
    }
发布了58 篇原创文章 · 获赞 31 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_37504771/article/details/89294261