连接池类:MyDataSource.java
- package com.itcast.myjdbc.pool;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
- import java.util.LinkedList;
- public class MyDataSource {
- private static final String url="jdbc:sqlserver://localhost:1433;DatabaseName=mytest";
- private static final String username="sa";
- private static final String password="123456";
- //LinkedListy用来添加链接,添加、删除元素比较快。
- private LinkedList<Connection> pool = new LinkedList<Connection>();
- private int initCount =5;//容器中初始化添加数目
- private int maxCount = 10;//容器中最大可以添加的数目
- int currentCount = 0;//当前使用的连接数
- public MyDataSource() {//初始化添加链接
- for(int i=0; i<initCount; i++) {
- this.pool.addLast(createConnection());
- this.currentCount++;
- }
- }
- public Connection getConnection() throws SQLException {//获取链接
- synchronized(pool) {
- if(this.pool.size()>0) {
- return pool.removeFirst();
- }
- if(this.currentCount<maxCount) {
- return createConnection();
- }
- throw new SQLException("已没有链接");
- }
- }
- public void free(Connection conn) {//释放链接
- pool.addLast(conn);
- }
- public Connection createConnection() {//创建连接
- Connection conns = null;
- try {
- conns = DriverManager.getConnection(url, username, password);
- } catch (SQLException e) {
- System.out.println("创建链接失败");
- }
- return conns;
- }
- public LinkedList<Connection> getPool() {
- return pool;
- }
- public void setPool(LinkedList<Connection> pool) {
- this.pool = pool;
- }
- }
测试类:Test .java
- package com.itcast.myjdbc.pool;
- import java.sql.Connection;
- import java.sql.SQLException;
- public class Test {
- public static void main(String[] args) throws SQLException {
- try {
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
- } catch (ClassNotFoundException e) {
- System.out.println("加载驱动失败");
- }
- MyDataSource myDatasource = new MyDataSource();
- for(int i=0; i<30; i++) {//输出三十个连接
- Connection conn = myDatasource.getConnection();
- System.out.println(conn);
- myDatasource.free(conn);
- }
- }
- }