operaciones por lotes JDBC

Declaración de interfaz de operación de entrada utilizando

Varias sentencias SQL en el lote, llame executeBatch () realiza método

Utilización en el método de calcular el consumo de tiempo currentTimeMillis (), y finalmente el uso al método commit () para enviar negocio

 

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();
            }
        }
    }

 

Publicado 58 artículos originales · ganado elogios 31 · Vistas a 40000 +

Supongo que te gusta

Origin blog.csdn.net/qq_37504771/article/details/89294261
Recomendado
Clasificación