JAVA---批量插入數據的操作


package java5.blob;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.junit.Test;

import java3.util.JDBCUtils;

/*
 * 	使用PreparedStatement實現批量數據的操作
 * update、delete本身就具有批量操作的效果
 * 所以主要研究如何用PreparedStatement實現更高效的批量插入
 */
public class InsertTest {
	//批量插入方式二:使用PreparedStatement
	@Test
	public void testInsert1() throws Exception{
		Connection conn=null;
		PreparedStatement ps=null;
		try {
			long start = System.currentTimeMillis();
			conn = JDBCUtils.getConnedtion();
			String sql="insert into goods(name)values(?)";
			ps = conn.prepareStatement(sql);
			for(int i=1;i<=200;i++){
				ps.setObject(1, "name_"+i);
				ps.execute();
			}
			long end = System.currentTimeMillis();
			
			System.out.println("花費的時間為:"+(end-start));
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.closeResource(conn, ps);
		}
		
	}
	
	/*
	 * 	批量插入的方式三:
	 * 1、addBatch()、executeBatch()、clearBatch()
	 * 2、mysql服務器默認關閉批處理,需要配置參數,讓mysql開啟批處理的支持
	 * 		?rewriteBatchedStatements=true  寫在配置文件的url后面
	 * 
	 */
	@Test
	public void testInsert2() throws Exception{
		Connection conn=null;
		PreparedStatement ps=null;
		try {
			long start = System.currentTimeMillis();
			
			conn = JDBCUtils.getConnedtion();
			String sql="insert into goods(name)values(?)";
			ps = conn.prepareStatement(sql);
			for(int i=1;i<=20000;i++){
				ps.setObject(1, "name_"+i);
				//1.贊sql
				ps.addBatch();
				if(i%500==0){
					//2.執行batch
					ps.executeBatch();
					//3.清空batch
					ps.clearBatch();
				}
			}
			
			long end = System.currentTimeMillis();
			System.out.println("花費的時間為:"+(end-start));
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			JDBCUtils.closeResource(conn, ps);
			
		}
		
	}
	
	//批量插入的方式四:設置連接不允許自動提交數據
	@Test
	public void testInsert3() throws Exception{
		Connection conn=null;
		PreparedStatement ps=null;
		try {
			long start = System.currentTimeMillis();
			
			conn = JDBCUtils.getConnedtion();
			conn.setAutoCommit(false);
			String sql="insert into goods(name)values(?)";
			ps = conn.prepareStatement(sql);
			for(int i=1;i<=20000;i++){
				ps.setObject(1, "name_"+i);
				
				//1.贊sql
				ps.addBatch();
				
				if(i%500==0){
					//2.執行batch
					ps.executeBatch();
					
					//3.清空batch
					ps.clearBatch();
				}
			}
			
			//提交數據
			conn.commit();
			
			long end = System.currentTimeMillis();
			System.out.println("花費的時間為:"+(end-start));
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			
			JDBCUtils.closeResource(conn, ps);
		}
		
		
		
	}
}


免責聲明!

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



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