1. 程式人生 > >java mysql dbcp連線池,批量更新速度慢的解決辦法:executeBatch

java mysql dbcp連線池,批量更新速度慢的解決辦法:executeBatch

1. url必須加上rewriteBatchedStatements=true

driverClassName=com.mysql.jdbc.Driver
#url= jdbc:mysql://192.168.0.184:3306/location?autoReconnect=true&useUnicode=true&characterEncoding=UTF8&allowMultiQueries=true&&useSSL=true&&rewriteBatchedStatements=true
url= jdbc:mysql://127.0.0.1:3306/location?autoReconnect=true&useUnicode=true&characterEncoding=UTF8&allowMultiQueries=true&&useSSL=true&&rewriteBatchedStatements=true
#username=111
username=root
password=123445
initialSize=5
maxTotal=80
maxIdle=10
minIdle=5
maxWaitMillis=5000
removeAbandonedOnMaintenance=true
removeAbandonedOnBorrow=true

removeAbandonedTimeout=1

2. 必須設定autoCommit為false

package com.hiexhibition.locate_engine_lite.db.mysql;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSourceFactory;

/**
 * DBCP配置類
 * @author SUN
 */
public class JdbcPool {
    
    private static Properties properties = new Properties();
    private static DataSource dataSource;
    //載入DBCP配置檔案
    JdbcPool(String filePath){
        try{
            FileInputStream is = new FileInputStream(filePath);  
            properties.load(is);
        }catch(IOException e){
            e.printStackTrace();
        }
        
        try{
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    //從連線池中獲取一個連線
    public Connection getConnection(){
        Connection connection = null;
        try{
            connection = dataSource.getConnection();
        }catch(SQLException e){
            e.printStackTrace();
        }
        try {
            connection.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
   
}

3. 呼叫addBatch之後和executeBatch之後,需要呼叫commit

public static void main(String[] args) throws SQLException {
		StoreRunnable storeRunnable = new StoreRunnable();
		final String TABLE_NAME = "user_position";		//使用者位置表
		
		Connection connection = DB.poolPosition.getConnection();		//資料庫連線
		Statement statement = connection.createStatement();
		for(int i = 0; i < 1000; i++){
			Position pt = new Position();
			Map map_insert = storeRunnable.getMapByPositionForDB(1123L, pt);		//要插入的map
			String insertSql = DB.getInsertSql(TABLE_NAME, map_insert);			//插入sql語句
			try {
				statement.addBatch(insertSql);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		long startTime = System.currentTimeMillis();
		statement.executeBatch();
		connection.commit();
		
		
		statement.close();
		System.out.println("耗時:" + (System.currentTimeMillis() - startTime));
	}