억 대 데이터 양 - JDBC 데이터베이스 삽입

 
package com.database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
 *       ,  JDBC  ,       .      
 *    、          , 100        jdbc  .
 *    、             , 5          .
 * @author Administrator
 */
public class Import {
	private static final String JDBC_URL = "jdbc:oracle:thin:@localhost:1521:orcl";
	private static final String JDBC_USER = "ttt";
	private static final String JDBC_PASSWORD = "pw123456";
	private static final String JDBC_SQL = "insert into tb_test (col1,col2) values (?,?)";
	
	public static void main(String[] args) throws Exception {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		exe(100000005);//1        
	}
	
	public static void exe(int sl) throws SQLException{
		int SIZE = 1000000;//      (   100 )
		int page = sl/SIZE;//    
		
		for (int i = 0; i < page; i++) {//    
			execute(i*SIZE,(i+1)*SIZE);
		}
		if(sl%SIZE != 0){
			execute(page*SIZE,sl);
		}
	}
	
	private static void execute(int begin, int end) throws SQLException {
		Connection conn = null;
		PreparedStatement pst= null;
		try {
			conn = DriverManager.getConnection(JDBC_URL, JDBC_USER,JDBC_PASSWORD);
			System.out.println("       :" + begin + " - " + end);
			
			conn.setAutoCommit(false);//        
			pst = conn.prepareStatement(JDBC_SQL);
			
			int recordNum = 0; //    
			int commit_size = 50000;//        5 
			for (int i = begin; i < end; i++) {
				recordNum++; //   
				pst.setString(1, "n" + i);
				pst.setString(2, "v" + i);
				pst.addBatch();
				if (recordNum % commit_size == 0) {
					pst.executeBatch();
					conn.commit();
					System.out.println("  :" + i);
					conn.setAutoCommit(false);
					pst = conn.prepareStatement(JDBC_SQL);
				}
			}
			if (recordNum % commit_size != 0) {
				pst.executeBatch();
				conn.commit();
				System.out.println("  :" + recordNum);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (pst != null) pst.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}finally{
				try{
					if (conn != null) conn.close();
					System.out.println("      !");
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

}



좋은 웹페이지 즐겨찾기