使用数据库连接池提高执行效率

利用数据库连接池可有效提高数据库操作效率,避免重复打开和关闭数据库连接。具体方法和测试结果如下:

首先建立一个属性文件,将相应的数据库连接方法加入其中:

属性文件具体设定如下:

driverClassName=oracle.jdbc.driver.OracleDriver
username=ORATEST
password=ORATEST
url=jdbc:oracle:thin:@vOracle.imStudio.com:1521:vOracle
poolSize=10

然后建立数据库连接池操作类ConnectionPoolTool.java

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

public class ConnectionPoolTool {
    
    private Vector<Connection> pool;
    private String url;
    private String username;
    private String password;
    private String driverClassName;

    /**
     * 连接池的大小,也就是连接池中有多少个数据库连接。
     */
    private int poolSize = 1;

    private static ConnectionPoolTool instance = null;

    /**
     * 私有的构造方法,禁止外部创建本类的对象,要想获得本类的对象,通过<code>getIstance</code>方法。
     * 使用了设计模式中的单子模式。
     */
    private ConnectionPoolTool() {
        init();
    }

    /**
     * 连接池初始化方法,读取属性文件的内容 建立连接池中的初始连接
     */
    private void init() {
        pool = new Vector<Connection>(poolSize);
        readConfig();
        addConnection();
    }

    /**
     * 返回连接到连接池中
     */
    public synchronized void release(Connection conn) {
        pool.add(conn);

    }

    /**
     * 关闭连接池中的所有数据库连接
     */
    public synchronized void closePool() {
        for (int i = 0; i < pool.size(); i++) {
            try {
                ((Connection) pool.get(i)).close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            pool.remove(i);
        }
    }

    /**
     * 返回当前连接池的一个对象
     */
    public static ConnectionPoolTool getInstance() {
        if (instance == null) {
            instance = new ConnectionPoolTool();
        }
        return instance;
    }

    /**
     * 返回连接池中的一个数据库连接
     */
    public synchronized Connection getConnection() { 
        if (pool.size() > 0) {
            Connection conn = pool.get(0);
            pool.remove(conn);
            return conn;
        } else {
            return null;
        }
    }

    /**
     * 在连接池中创建初始设置的的数据库连接
     */
    private void addConnection() {
        Connection conn = null;
        for (int i = 0; i < poolSize; i++) {

            try {
                Class.forName(driverClassName);
                conn = java.sql.DriverManager.getConnection(url, username, password);
                pool.add(conn);

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 读取设置连接池的属性文件
     */
    private void readConfig() {
        try {
            String path = System.getProperty("user.dir") + "\dbpool.properties";
            FileInputStream is = new FileInputStream(path);
            Properties props = new Properties();
            props.load(is);
            this.driverClassName = props.getProperty("driverClassName");
            this.username = props.getProperty("username");
            this.password = props.getProperty("password");
            this.url = props.getProperty("url");
            this.poolSize = Integer.parseInt(props.getProperty("poolSize"));
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("读取属性文件出错. ");        
        }
    }

}

再加入数据库连接池测试方法ConnectionPoolTest.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class ConnectionPoolTest {

    /**
     * @param args
     */
    public static void main(String[] args)throws Exception {
        // TODO Auto-generated method stub
        String sql = "select userid,username,password from tbluser";
        long start = System.currentTimeMillis();
        ConnectionPoolTool pool = null;

        for (int i = 0; i < 100; i++) {
            pool = ConnectionPoolTool.getInstance();
            Connection conn = pool.getConnection();
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
            }
            rs.close();
            stmt.close();
            pool.release(conn);
        }
        pool.closePool();
        System.out.println("经过100次的循环调用,使用连接池花费的时间:" + (System.currentTimeMillis() - start) + "ms
");

        String hostName = "vOracle.imStudio.com";
        String driverClass = "oracle.jdbc.driver.OracleDriver";
        String url = "jdbc:oracle:thin:@" + hostName + ":1521:vOracle";
        String user = "ORATEST";
        String password = "ORATEST";
        start = System.currentTimeMillis();
        
        for (int i = 0; i < 100; i++) {
            Class.forName(driverClass);
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
            }
            rs.close();
            stmt.close();
            conn.close();
        }
        System.out.println("经过100次的循环调用,不使用连接池花费的时间:" + (System.currentTimeMillis() - start) + "ms");
    }

}

编写完成后,进行测试运行,如下为我本机测试结果:

原文地址:https://www.cnblogs.com/songhaipeng/p/3307286.html