JDBC--批处理操作数据库

一次处理多条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();
            }
        }
        
        

    }

}

 

posted @ 2018-04-18 19:19  Cappuccinom  阅读(198)  评论(0编辑  收藏  举报