JDBC 连接池源代码

本文介绍了一个简单的Java数据库连接池实现,通过预创建多个数据库连接并维护在一个连接池中,以提高应用程序的性能和响应速度。当需要使用数据库连接时,从连接池中获取一个空闲连接,使用完毕后再归还到连接池。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 package com.curriculumDesign.database;
2
3 import java.sql.Connection;
4 import java.sql.DriverManager;
5 import java.util.ArrayList;
6
7 public class ConnectionPool {
8
9 private static int maxConnectNum = 10;
10
11 private java.sql.Connection conn[] = new Connection[maxConnectNum];
12
13 private static ArrayList connectPool = new ArrayList();
14
15 private static int flag = 0;
16
17 public ConnectionPool() {
18 if (flag == 0) {
19 init();
20 }
21 }
22
23 private Connection getConnectionFromDatabase() {
24 Connection trueConn = null;
25 try {
26 Class.forName("com.mysql.jdbc.Driver").newInstance();
27 String url = "jdbc:mysql://localhost:3306/book_store?user=root&password=";
28 trueConn = DriverManager.getConnection(url);
29 } catch (Exception ex) {
30 System.out.println("数据连接出错了:" + ex.toString());
31 }
32 return trueConn;
33 }
34
35 //这里建立所有的连接;
36 private void init() {
37 for (int i = 0; i < maxConnectNum; i++) {
38 conn[i] = getConnectionFromDatabase();
39 connectPool.add(i, conn[i]);
40 }
41 flag = 1;
42 }
43
44 //从连接池中取得一个可用的连接
45 public Connection getConnection() {
46 Connection conn = null;
47 if (connectPool.size() == 0) {
48 try {
49 java.lang.Thread.sleep(1000);
50 getConnection();
51 } catch (InterruptedException ex) {
52 System.out.println("连接全部用光,这里sleep出错了.");
53 }
54 } else {
55 conn = (Connection) connectPool.remove(0);
56 }
57
58 return conn;
59 }
60
61 //提供给外部程序调用,不用的连接放回连接池当中...
62 public boolean release(Connection conn) {
63 return connectPool.add(conn);
64 }
65 }

摘抄别人的,并非原创

转载于:https://www.cnblogs.com/c840136/articles/jdbc_connection_pool.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值