JDBC——数据库连接池

概念:一个容器(集合),存放数据库连接的容器

当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完后,会将连接对象归还给容器

好处

节约资源
用户访问高效

实现

  1. 标准接口:DataSource javax.sql包下的
    方法:
    (1)获取连接:getConnection()
    (2)归还连接:Connection.close()。如果连接对象Connection是从连接池中提供,那么调用Connection.close()方法,则不会再关闭连接了。而是归还连接
  2. 一般由数据库厂商来实现
    C3P0:数据库连接池技术
    Druid:数据库连接池实现技术,由阿里巴巴提供

C3P0:数据库连接池技术

步骤

  1. 导入jar包 c3p0-0.9.5.2.jar和mchange-commons-java-0.2.12.jar
    (也要添加数据库连接jar包)
  2. 定义配置文件:
    名称:c3p0.properties 或者 c3p0-config.xml
    路径:直接将文件放在src文件目录下
  3. 创建核心对象 数据库连接池对象 ComboPooledDataSource
  4. 获取连接:getConnection

代码实现

在这里插入图片描述

Druid:数据库连接池实现技术,由阿里巴巴提供

步骤

  1. 导入jar包 druid-1.0.9.jar
    (也要添加数据库连接jar包)
  2. 定义配置文件
    properties形式
    可以为任意名称,放在任意目录下
  3. 加载配置文件 properties
  4. 获取数据库连接池对象:通过工厂来获取 DruidDataSourceFactory
  5. 获取连接:getConnection

在这里插入图片描述

定义工具类

  1. 定义一个类 JDBCUtils
  2. 提供静态代码块加载配置文件,初始化连接池对象
  3. 提供方法
    获取连接方法:通过数据库连接池获取连接
    释放资源
    获取连接池的方法
  4. 工具类:
package org.ccit.util;
/**
 * Druid连接池的工具类
 * @author yinshuang
 *
 */

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class JDBCUtils {
	//1.定义成员变量 DataSource
	private static DataSource ds;
	
	static {
		try {
			//1.加载配置文件
			Properties pro = new Properties();
			pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));

			//2.获取DataSource
			ds = DruidDataSourceFactory.createDataSource(pro);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取连接
	 * @throws SQLException 
	 */
	public static Connection getConnection() throws SQLException {
		return ds.getConnection();
	}
	
	/**
	 * 释放资源
	 */
	public static void close(Statement stmt,Connection conn) {
		close(null, stmt, conn);
	}
	
	/**
	 * 释放资源
	 */
	public static void close(ResultSet rs,Statement stmt,Connection conn) {
		if(rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(stmt != null) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if(conn != null) {
			try {
				conn.close();//归还连接
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 获取连接池方法
	 */
	public static DataSource getDataSource() {
		return ds;
	}
}

工具类测试

package org.ccit.druid;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import org.ccit.util.JDBCUtils;

/**
 * 使用新的工具类
 * @author yinshuang
 *
 */
public class DruidDemo2 {
	public static void main(String[] args) {
		/**
		 * 添加操作:添加一条记录
		 */
		Connection conn = null;
		PreparedStatement pstmt = null;
		try {
			//1. 获取连接
			conn = JDBCUtils.getConnection();
			//2.定义sql
			String sql = "insert into goods value(null,?,?,?,?)";
			//3.获取prepareStatement对象
			pstmt = conn.prepareStatement(sql);
			//4.给 ? 赋值
			pstmt.setString(1, "橙汁");
			pstmt.setInt(2, 30);
			pstmt.setDate(3, null);
			pstmt.setDouble(4, 50.5);
			//5.执行sql
			int count = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			//6.释放资源
			JDBCUtils.close(pstmt, conn);
		}
	}
}

JDBCTemplate

Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发

步骤:

  1. 导入jar包
  2. 创建JdbcTemplate对象。依赖于数据源DataSource
    JdbcTemplate template = new JdbcTemplate(ds);

调用JdbcTemplate的方法来完成CRUD的操作

  1. update():执行DML语句。增、删、改语句
  2. queryForMap():查询结果将结果集封装为map集合
    key = 列名; value = 值 将这条记录封装为一个map集合
    注:查询的结果集长度只能为1
  3. queryForList():查询结果将结果集封装为list集合
    注:将每一条记录封装在一个Map集合中,再将Map集合装载到List集合中
  4. query():查询结果,将结果封装到JavaBean对象
    query的参数:RowMapper
    一般使用BeanPropertyRowMapper实现类,可完成数据到JavaBean的自动封装
    new BeanPropertyRowMapper<类型>(类型.class)
  5. queryForObject:查询结果,将结果封装为对象
    一般用于聚合函数的查询

demo

  1. 将id=1的cnt 修改为100
  2. 添加一条记录
  3. 删除记录
  4. 查询id=1的记录,将其封装为map集合
  5. 查询所有记录,将其封装在List集合
  6. 查询所有记录,将其封装在Goods对象的List集合
  7. 查询总记录数
package org.ccit.entity;

import java.util.Date;

public class Goods {
	private int id;
	private String name;//名字
	private int cnt;//数量
	private Date best_date;//有效期
	private double price;//价格
	
	public Goods() {
		super();
	}
	
	public Goods(int id, String name, int cnt, Date best_date, double price) {
		super();
		this.id = id;
		this.name = name;
		this.cnt = cnt;
		this.best_date = best_date;
		this.price = price;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getCnt() {
		return cnt;
	}

	public void setCnt(int cnt) {
		this.cnt = cnt;
	}

	public Date getBest_date() {
		return best_date;
	}

	public void setBest_date(Date best_date) {
		this.best_date = best_date;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	@Override
	public String toString() {
		return "Goods [id=" + id + ", name=" + name + ", cnt=" + cnt + ", best_date=" + best_date + ", price=" + price
				+ "]";
	}
	
}
package org.ccit.template;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.ccit.entity.Goods;
import org.ccit.util.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

public class JdbcTemplateDemo2 {

	//1.获取JDBCTemplate对象
	private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
	
	@Test
	/**
	 * 1.将id=1的cnt 修改为100
	 */
	public void test1() {
		
		//2.定义sql
		String sql = "update goods set cnt=100 where id=1";
		//3.执行sql
		int count = template.update(sql);
		System.out.println(count);	
	}
	
	@Test
	/**
	 * 2.添加一条记录
	 */
	public void test2() {
		String sql = "insert into goods values(default,?,?,?,?)";
		int count = template.update(sql,"火腿",50,"2021-09-03",56.2);
		System.out.println(count);
	}
	
	@Test
	/**
	 * 3.删除记录
	 */
	public void test3() {
		String sql = "delete from goods where name=?";
		int count = template.update(sql,"火腿");
		System.out.println(count);
	}
	
	@Test
	/**
	 * 4.查询id=1的记录,将其封装为map集合
	 * 注:查询的结果集长度只能为1
	 */
	public void test4() {
		String sql = "select * from goods where id=?";
		//key:列名	value:值
		Map<String, Object> map = template.queryForMap(sql,1);
		System.out.println(map);
		//{id=1, name=面包, cnt=100, best_date=null, price=99.1}
	}
	
	@Test
	/**
	 * 5.查询所有记录,将其封装在List集合
	 */
	public void test5() {
		String sql = "select * from goods";
		List<Map<String, Object>> list = template.queryForList(sql);
		
		for(Map<String, Object> map :list) {
			System.out.println(map);
		} 
	}
	
	@Test
	/**
	 * 6_1.查询所有记录,将其封装在Goods对象的List集合
	 */
	public void test6_1() {
		String sql = "select * from goods";
		List<Goods> list = template.query(sql, new RowMapper<Goods>() {

			@Override
			public Goods mapRow(ResultSet rs, int i) throws SQLException {
				int id = rs.getInt("id");
				String name = rs.getString("name");
				int cnt = rs.getInt("cnt");
				Date best_date = rs.getDate("best_date");
				double price = rs.getDouble("price");
				
				Goods goods = new Goods(id, name, cnt, best_date, price);
				return goods;
			}
		});
		for(Goods goods:list) {
			System.out.println(goods);
		}	
	}
	
	@Test
	/**
	 * 6_2.查询所有记录,将其封装在Goods对象的List集合
	 */
	public void test6_2() {
		String sql = "select * from goods";
		List<Goods> list = template.query(sql, new BeanPropertyRowMapper<Goods>(Goods.class));
		for(Goods goods : list) {
			System.out.println(goods);
		}
	}
	

	@Test
	/**
	 *7.查询总记录数
	 */
	public void test7() {
		String sql = "select count(id) from goods";
		Long total = template.queryForObject(sql, Long.class);
		System.out.println(total);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值