本文主要是介绍自己实现数据库连接池,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
jdbc连接据库步骤中,最耗时的是建立连接的过程,所以可以把已经建立的连接存起来,等下回使用的时候在拿来使用,这样就能省好多时间。开源的数据库连接池也有很多,dbcp,c3p0等。下面自己简单实现数据库连接池建立和释放的过程。
package com.datasource;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;public class MyDataSource {private String jdbcDriver; // 数据库驱动private String dbUrl = "jdbc:mysql://localhost:3306/db"; // 数据 URL private String dbUsername = "root"; // 数据库用户名private String dbPassword = "root"; // 数据库用户密码private static int initCount = 5;//初始数量private static int maxCount = 10;//最大连接数private static int currentCount = 0;//当前连接数//因为是要频繁的增删,所以用LinkedListprivate LinkedList<Connection> connectionsPool = new LinkedList<Connection>();//构造方法建立多个连接public MyDataSource() {for (int i = 0; i < initCount; i++) {try {this.connectionsPool.addLast(this.createConnection());this.currentCount ++;} catch (SQLException e) {throw new ExceptionInInitializerError(e);}}}//创建连接private Connection createConnection() throws SQLException {return DriverManager.getConnection(dbUrl, dbUsername, dbPassword);}//获取连接public Connection getConnection() throws SQLException {synchronized (connectionsPool) {if (this.connectionsPool.size() > 0)return this.connectionsPool.removeFirst();if (this.currentCount < maxCount) {this.currentCount++;return this.createConnection();}throw new SQLException("已没有链接");}}//释放资源 把连接放回到链接池中public void free(Connection conn) {this.connectionsPool.addLast(conn);}}
package com.datasource;import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;public class JDBCUtils {public static MyDataSource dataSource = null;//空构造方法public JDBCUtils() {}//静态代码块static{try {//加载驱动Class.forName("com.mysql.jdbc.Driver");dataSource = new MyDataSource();} catch (ClassNotFoundException e) {e.printStackTrace();}}//得到连接public Connection getConnection() throws Exception {return dataSource.getConnection();}//释放资源public static void free(ResultSet rs, Statement st, Connection conn) {try {if (rs != null) {rs.close();}} catch (SQLException e) {e.printStackTrace();}finally{try {if (st != null) {st.close();}} catch (Exception e2) {e2.printStackTrace();}finally{if (conn != null) {dataSource.free(conn);}}}}
}
测试
package com.datasource;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;public class Test {static Connection conn = null;static PreparedStatement ps = null;static ResultSet rs = null;public static void main(String[] args) throws Exception {JDBCUtils utils = new JDBCUtils();conn = utils.getConnection();String sql = "select * from user";ps = conn.prepareStatement(sql);rs = ps.executeQuery();while (rs.next()) {System.out.println(rs.getString("user_name"));}utils.free(rs, ps, conn);}}
同时建立10个连接时可以的,但是再建第11个时,就会抛出异常了,因为设置的最大连接数是10.
这篇关于自己实现数据库连接池的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!