5 语句批处理(Batch)

import java.sql.*;

/**
 * 批处理Batch
 * @author Administrator
 *
 */
public class TestBatch {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            //1:加载驱动类
            Class.forName("com.mysql.jdbc.Driver");
            
            //2:建立连接(连接对象内部其实包含Socket对象,是一个远程的连接,比较耗时,这是Connection对象管理的一个要点)
            //真正的开发中,都会使用连接池来管理对象
            conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test","root","123456");
            
            //将事务设为手动提交
            conn.setAutoCommit(false);
            long start = System.currentTimeMillis();
            stmt = conn.createStatement();
            
            for(int i=0; i<20000;i++){
                stmt.addBatch("insert into user (name,age) values ('TFBoy吃屎"+i+"',12)");
            }
            stmt.executeBatch();
            
            //提交事务
            conn.commit();
            
            long end = System.currentTimeMillis();
            System.out.println("插入两万行TFBoy吃屎,耗时(毫秒):" + (end-start));
            
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally{
            
            //关闭顺序遵循:ResultSet-->Statement->Connection
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容