欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java--JDBC--批处理操作数据库

程序员文章站 2022-10-06 18:13:00
一次处理多条mysql语句 ......

一次处理多条mysql语句

package com.machuang.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Demo14 {

    public static void main(String[] args) {
        
        Connection conn = null;
        Statement st = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            
            // 建立连接
            conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/testjdbc", "root", "333666");
            
            conn.setAutoCommit(false);        // 设置手动递交
            st = conn.createStatement();
            
            for (int i = 0; i < 2000; i++) {
                st.addBatch("insert into t_usr (usrName, pwd, regTime) value ('Cappuccino"+i+"', '64648', now())");
            }
            st.executeBatch();
            
            conn.commit(); //递交
            
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if(null != st) {
                    st.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if(null != conn) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
        

    }

}