数据库连接池
其实就是一个容器(集合),存放数据库连接的容器。
当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库时,从容器中获取连接对象,用户访问完之后,会将连接对象归还给容器。
好处:
-
节约资源
-
用户访问高效
-
标准接口:DataSource javax.sql包下的
- 方法:
- 获取连接:getConnection()
- 归还连接:Connection.close()。如果连接对象Connection是从连接池中获取的,那么调用Connection.close()方法,则不会再关闭连接了。而是归还连接
- 一般我们不去实现它,有数据库厂商来实现
- C3P0:数据库连接池技术
- Druid:数据库连接池实现技术,由阿里巴巴提供的
- 方法:
/* C3P0:数据库连接池技术
https://sourceforge.net/projects/c3p0/files/latest/download?source=files
* 步骤:
1. 导入jar包 (两个) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,
2. 定义配置文件:
* 名称: c3p0.properties 或者 c3p0-config.xml
* 路径:直接将文件放在src目录下即可。
3. 创建核心对象 数据库连接池对象 ComboPooledDataSource
4. 获取连接: getConnection
*/
public class C3p0Demo {
public static void main(String[] args) throws SQLException {
//1.创建数据库连接池对象
DataSource dataSource = new ComboPooledDataSource();
//2. 获取连接对象
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select * from student2");
ResultSet resultSet = preparedStatement.executeQuery();
List<Student> list = new ArrayList<>();
while(resultSet.next()){
Student student = new Student();
student.setId(resultSet.getInt(1));
student.setName(resultSet.getString(2));
student.setAge(resultSet.getInt(3));
student.setSex(resultSet.getString(4));
list.add(student);
}
for (Student a:list) {
System.out.println(a);
}
connection.close();
}
}
/*
5. Druid:数据库连接池实现技术,由阿里巴巴提供的
https://github.com/alibaba/druid
1. 步骤:
1. 导入jar包 druid-1.0.9.jar
2. 定义配置文件:
* 是properties形式的
* 可以叫任意名称,可以放在任意目录下
3. 加载配置文件。Properties
4. 获取数据库连接池对象:通过工厂来来获取 DruidDataSourceFactory
5. 获取连接:getConnection
*/
public class DruidDemo {
public static void main(String[] args) throws Exception {
//3.加载配置文件
Properties pro = new Properties();
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//4.获取连接池对象
DataSource dataSource = DruidDataSourceFactory.createDataSource(pro);
//5.获取连接
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select * from student2");
ResultSet resultSet = preparedStatement.executeQuery();
List<Student> list = new ArrayList<>();
while(resultSet.next()){
Student student = new Student();
student.setId(resultSet.getInt(1));
student.setName(resultSet.getString(2));
student.setAge(resultSet.getInt(3));
student.setSex(resultSet.getString(4));
list.add(student);
}
for (Student a:list) {
System.out.println(a);
}
connection.close();
}
}
定义工具类
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
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 (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getCon() throws SQLException {
return ds.getConnection();
}
public static DataSource getDs() throws SQLException {
return ds;
}
public static void close(Statement stmt, Connection conn){
close(null,stmt,conn);
}
public static void close(ResultSet resultSet, Statement stmt, Connection conn){
if(conn != null){
try {
conn.close();//归还连接
} catch (SQLException e) {
e.printStackTrace();
}
}
if(resultSet != null){
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Spring JDBC
Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
步骤:
-
导入jar包
-
创建JdbcTemplate对象。依赖于数据源DataSource
- JdbcTemplate template = new JdbcTemplate(ds);
-
调用JdbcTemplate的方法来完成CRUD的操作
- update():执行DML语句。增、删、改语句
- queryForMap():查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合
- 注意:这个方法查询的结果集长度只能是1
- queryForList():查询结果将结果集封装为list集合
- 注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中
- query():查询结果,将结果封装为JavaBean对象
- 一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
- new BeanPropertyRowMapper<类型>(类型.class)
- queryForObject:查询结果,将结果封装为对象
- 一般用于聚合函数的查询
public class SpringJDBCDemo {
private JdbcTemplate jdbcTemplate;
@Before
public void init() throws SQLException {
jdbcTemplate=new JdbcTemplate(JDBCUtils.getDs());
}
@Test
public void testAdd(){
jdbcTemplate.update("insert into student2(id,name,age,sex) values(?,?,?,?)",5,"赵六",10,"男");
}
@Test
public void testUpdate(){
jdbcTemplate.update("update student2 set age = ? where id = ?",16,5);
}
@Test
public void testDelete(){
jdbcTemplate.update("delete from student2 where id =?",5);
}
@Test
public void testFindOne(){
List<Student> list = jdbcTemplate.query("select * from student2 where id =?", new BeanPropertyRowMapper<Student>(Student.class),7);
for (Student a:list
) {
System.out.println(a);
}
}
@Test
public void testFindAll(){
List<Student> list = jdbcTemplate.query("select * from student2 ", new BeanPropertyRowMapper<Student>(Student.class));
for (Student a:list
) {
System.out.println(a);
}
}
@Test
public void testFindCount(){
int count = jdbcTemplate.queryForObject("select count(*) from student2",Integer.class);
System.out.println(count);
}
}
补充:追光者数据库连接池(Hikari)
import com.sibd.pojo.Student;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class HikariCPDemo {
public static void main(String[] args) throws SQLException {
HikariConfig hikariConfig = new HikariConfig("src/hikari.properties");
HikariDataSource ds = new HikariDataSource(hikariConfig);
Connection conn = null;
Statement statement = null;
ResultSet rs = null;
conn = ds.getConnection();
statement = conn.createStatement();
rs = statement.executeQuery("select * from student2");
while (rs.next()){
Student student = new Student();
student.setId(rs.getInt(1));
student.setName(rs.getString(2));
student.setAge(rs.getInt(3));
student.setSex(rs.getString(4));
System.out.println(student);
}
rs.close();
statement.close();
conn.close();
}
}