数据库连接 -- 执行完毕 -- 释放
连接-- 释放 是十分浪费系统资源的
池化技术:准备一些预先的资源,过来就连接预先准备好的
编写连接池,实现一个接口DataSource
使用了这些数据库连接池之后,我们在项目开发中就不需要编写连接数据库的代码了
需要用到的jar包
配置文件dbcp.properties
- #连接设置
- driverClassName=com.mysql.jdbc.Driver
- url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
- username=root
- password=123456
-
- #初始化连接
- initialSize=10
-
- #最大连接数量
- maxActive=50
-
- #最大空闲连接
- maxIdle=20
-
- #最小空闲连接
- minIdle=5
-
- #超时等待时间以毫秒为单位 6000毫秒/1000等于60秒
- maxWait=60000
- #JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:【属性名=property;】
- #注意:user 与 password 两个属性会被明确地传递,因此这里不需要包含他们。
- connectionProperties=useUnicode=true;characterEncoding=UTF8
-
- #指定由连接池所创建的连接的自动提交(auto-commit)状态。
- defaultAutoCommit=true
-
- #driver default 指定由连接池所创建的连接的只读(read-only)状态。
- #如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
- defaultReadOnly=
-
- #driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
- #可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
- defaultTransactionIsolation=READ_COMMITTED
工具类
- import org.apache.commons.dbcp.BasicDataSourceFactory;
-
- import javax.sql.DataSource;
- import java.io.InputStream;
- import java.sql.*;
- import java.util.Properties;
-
-
- public class JdbcUtils_DBCP {
- private static DataSource dataSource = null;
-
- static {
- try {
- InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcp.properties");
- Properties properties = new Properties();
- properties.load(in);
-
- //创建数据源 工厂模式--->创建对象
- dataSource = BasicDataSourceFactory.createDataSource(properties);
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 获取连接
- */
- public static Connection getConnection() throws SQLException {
- return dataSource.getConnection(); //从数据源中获取连接
- }
-
- /**
- * 释放资源
- */
- public static void release(Connection con, Statement st, ResultSet rs) {
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if (st != null) {
- try {
- st.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if (con != null) {
- try {
- con.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- }
测试类
- import com.yuan.lesson02.utils.JdbcUtils;
-
- import java.sql.Connection;
- import java.sql.PreparedStatement;
- import java.sql.SQLException;
-
- public class TestDBCP {
- public static void main(String[] args) {
- Connection connection = null;
- PreparedStatement preparedStatement = null;
-
- try {
- connection = JdbcUtils.getConnection();
- // PreparedStatement 与 Statement 的区别
- //使用 ? 占位符替代
- String sql = "INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`) VALUES (?,?,?,?,?)";//预编译,SQL,先写SQL,然后不执行
- preparedStatement = connection.prepareStatement(sql);
- //手动给参数赋值
- preparedStatement.setInt(1, 4);
- preparedStatement.setString(2, "牛六");
- preparedStatement.setString(3, "123456");
- preparedStatement.setString(4, "niuliu@sina.com");
- preparedStatement.setDate(5, new java.sql.Date(new java.util.Date().getTime()));
- int num = preparedStatement.executeUpdate();
- if (num > 0) {
- System.out.println("插入成功!");
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- JdbcUtils.release(connection, preparedStatement, null);
- }
- }
- }
需要用到的jar包
配置文件c3p0-config.xml
- "1.0" encoding="UTF-8"?>
-
- <default-config>
-
"driverClass">com.mysql.jdbc.Driver -
"jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC -
"user">root -
"password">123456 -
"acquiredIncrement">5 -
"initialPoolSize">10 -
"minPoolSize">5 -
"maxPoolSize">20 - default-config>
-
-
-
-
"MySQL"> -
"driverClass">com.mysql.jdbc.Driver -
"jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC -
"user">root -
"password">123456 -
"acquiredIncrement">5 -
"initialPoolSize">10 -
"minPoolSize">5 -
"maxPoolSize">20 -
工具类
- import com.mchange.v2.c3p0.ComboPooledDataSource;
- import org.apache.commons.dbcp.BasicDataSourceFactory;
-
- import javax.sql.DataSource;
- 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 JdbcUtils_C3P0 {
- private static ComboPooledDataSource comboPooledDataSource = null;
-
- static {
- try {
- //代码版配置
- // comboPooledDataSource = new ComboPooledDataSource();
- // comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
- // comboPooledDataSource.setUser("root");
- // comboPooledDataSource.setPassword("123456");
- // comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/jdbcstudy");
- // comboPooledDataSource.setInitialPoolSize(5);
- // comboPooledDataSource.setMaxPoolSize(10);
- // comboPooledDataSource.setMinPoolSize(5);
-
-
-
- //创建数据源 工厂模式--->创建对象
- comboPooledDataSource = new ComboPooledDataSource("MySQL"); //配置文件写法
-
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * 获取连接
- */
- public static Connection getConnection() throws SQLException {
- return comboPooledDataSource.getConnection(); //从数据源中获取连接
- }
-
- /**
- * 释放资源
- */
- public static void release(Connection con, Statement st, ResultSet rs) {
- if (rs != null) {
- try {
- rs.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if (st != null) {
- try {
- st.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- if (con != null) {
- try {
- con.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- }
- }
测试类
- public class TestC3P0 {
- public static void main(String[] args) {
- Connection connection = null;
- PreparedStatement preparedStatement = null;
-
- try {
- connection = JdbcUtils_C3P0.getConnection();
- // PreparedStatement 与 Statement 的区别
- //使用 ? 占位符替代
- String sql = "INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`) VALUES (?,?,?,?,?)";//预编译,SQL,先写SQL,然后不执行
- preparedStatement = connection.prepareStatement(sql);
- //手动给参数赋值
- preparedStatement.setInt(1, 6);
- preparedStatement.setString(2, "牛六");
- preparedStatement.setString(3, "123456");
- preparedStatement.setString(4, "niuliu@sina.com");
- preparedStatement.setDate(5, new java.sql.Date(new java.util.Date().getTime()));
- int num = preparedStatement.executeUpdate();
- if (num > 0) {
- System.out.println("插入成功!");
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- JdbcUtils.release(connection, preparedStatement, null);
- }
- }
- }
无论用什么数据源,本质还是一样的,DataSource接口不会变,方法就不会变。