MySQL開啟批處理


MySQL默認關閉批處理

開啟方法

在原始的URL尾部添加開啟指令,如下標注語句
url = jdbc:mysql://localhost:3306/mydb3 ?rewriteBatchedStatements=true

添加批處理

調用preparedStatement中的addBatch()方法,將一句sql添加到批中,循環調用,則可添加大量sql語句到批中。

執行批處理

調用executeBatch()方法,此方法為繼承父類Statament中的方法。

批處理可將sql的執行效率大大提升

范例代碼

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import cn.itcast.jdbcUtils.JdbcUtils;

public class Demo5 {
	/**
	 * 批處理
	 * pstmt對象內部有集合
	 * 1.用循環向pstmt中添加sql參數,它有自己的模板,使用一組參數與模板可以匹配出一條sql語句
	 * 2.最后調用執行批方法,完成向數據庫發送
	 * @throws Exception 
	 */
	public void fun5() throws Exception {
		/*
		 * pstmt:
		 * >添加參數到批中
		 * >執行批
		 */
		
		Connection con = JdbcUtils.getConnection();
		String sql = "insert into t_stu values(?,?,?,?)";
		PreparedStatement pstmt = (PreparedStatement) con.prepareStatement(sql);
		
		//批量添加數據
		for(int i = 0;i < 10000;i++) {
			pstmt.setInt(1, i+1);
			pstmt.setString(2, "stu_"+i);
			pstmt.setInt(3, i);
			pstmt.setString(4,i%2==0? "男":"女");
			
			pstmt.addBatch();//添加批,這一組參數就保存到集合中了
		}
		long start = System.currentTimeMillis();
		pstmt.executeBatch();//執行批
		long end = System.currentTimeMillis();
		System.out.println(end-start);
	}
	
	
	public static void main(String[] args) throws Exception {
		Demo5 demo5 = new Demo5();
		demo5.fun5();
	}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM