Java基础--JDBC(数据库连接--使用连接池)

/**
 * 使用连接池连接数据库
 * @author 
 */
public class MyDataSource implements DataSource {
	//1.创建容器用于放置的Connection对象--因为频繁的操作添加和删除所以使用LinkedList对象
	private static LinkedList<Connection> ls = new LinkedList<>();
	
	static {
		//创建连接并添加到容器中
		for (int i = 0; i <= 6; i++) {
			//获取连接
			Connection conn = JdbcUtils.getConnection();//此时连接方法、已经封装成工具类
			ls.add(conn);
		}
	}
	
	@Override
	public Connection getConnection() throws SQLException {
		Connection conn = null;
		if (ls.size() == 0) {
			for (int i = 0; i <= 6; i++) {
				//获取连接
				conn = JdbcUtils.getConnection();
				//添加Connection对象到linkedList对象
				ls.add(conn);
			}
		}
		//拿到一个Connection对象
		conn = ls.removeFirst();
		return conn;
	}
	
	/**
	 * 调用完之后放回容器--释放资源
	 * @param conn
	 */
	public static void addSqlClose(Connection conn) {
		if(conn != null)
		ls.add(conn);
	}
	

	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		// TODO Auto-generated method stub
		return false;
	}
	
	@Override
	public Connection getConnection(String username, String password) throws SQLException {
		return null;
	}

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public int getLoginTimeout() throws SQLException {
		// TODO Auto-generated method stub
		return 0;
	}
	
}

注意:上面是实现了DataSource 接口,所以要覆写接口中的方法,这里由于时间的问题,只覆写了getConnection方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值