侧边栏壁纸
博主头像
王小木人个人技术文章记录

这是很长,很好的一生

  • 累计撰写 141 篇文章
  • 累计创建 43 个标签
  • 累计收到 10 条评论

目 录CONTENT

文章目录

java 利用连接池创建连接

王小木人个人技术文章记录
2021-05-26 / 0 评论 / 0 点赞 / 1,764 阅读 / 1,589 字
​
package com.market.util;

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

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class ConnectionManager {
	private static DataSource datasource = null;
	private static ThreadLocal<Connection> threadlocal = new ThreadLocal<Connection>();
	static {
		Properties prop = new Properties();
		try {
			prop.load(new FileInputStream("src//ConnectInfo.properties"));
			
			datasource = BasicDataSourceFactory.createDataSource(prop);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Connection getConnection() {
		Connection conn = threadlocal.get();
		if (conn == null) {
			try {
				conn = datasource.getConnection();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			threadlocal.set(conn);
		}
		return conn;
	}
	public static void closeConnection()
	{
		Connection conn=threadlocal.get();
		if(conn!=null)
		{
			threadlocal.remove();
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

​

创建连接需要的包
1.png

0

评论区