zoukankan      html  css  js  c++  java
  • JDBC 复习4 批量执行SQL

    1使用jdbc进行批量执行SQL在实际的项目开发中,有时候需要向数据库发送一批SQL语句执行,这时应避免向数据库一条条的发送执行,而应采用JDBC的批处理机制,以提升执行效率。

    package dbex.mysql;
    
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.Date;
    
    import dbex.DBUtil;
    
    public class BatchSQL {
    
    	/**
    	 * @throws IOException 
    	 * @throws SQLException 
    	 * @Title: doBatch 
    	 * @Description: 使用JDBC进行批处理操作
    	 * @param     
    	 * @throws
    	 */
    	void doBatch() throws SQLException, IOException{
    		Connection conn=DBUtil.getConnection();
    		PreparedStatement ppst = null;
    		ResultSet rs = null;
    		try {
    			long startTime = System.currentTimeMillis();
    			ppst = conn.prepareStatement("insert into clob values(?,'this is a test for batch sql')");
    			for (int i = 222; i < 100222; i++) {
    				ppst.setInt(1, i);
    				ppst.addBatch();
    			}
    			ppst.executeBatch();
    			long endTime = System.currentTimeMillis();
    			System.out.println(new Date().toLocaleString()+ "执行批量一共耗时"+(endTime-startTime)/1000+"s");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			DBUtil.closeAll(conn, ppst, rs);
    		}
    	}
    	public static void main(String[] args) throws SQLException, IOException {
    		new BatchSQL().doBatch();
    	}
    }
    
    
    

    优点

    • SQL是预编译之后的 执行效率有保证

    缺点

    • 这种形式只能应用在批量的插入数据或者批量更新的情况下
  • 相关阅读:
    数据库 | 建表常用语句
    心得 | 撰写项目申报书
    工具 | 时间转化
    SpringBoot | 启动异常 | 显示bulid success 无 error信息
    120. 三角形最小路径和
    63. 不同路径 II
    SpringBoot | Velocity template
    SpringBoot | quartz | @DisallowConcurrentExecution
    SpringBoot | Hibernate @Transient 注解
    Java | 基础归纳 | 静态方法与实例方法的区别
  • 原文地址:https://www.cnblogs.com/humi/p/7919826.html
Copyright © 2011-2022 走看看