• DBCP 与 C3P0连接池


            数据库连接 -- 执行完毕 -- 释放

            连接-- 释放 是十分浪费系统资源的

            池化技术:准备一些预先的资源,过来就连接预先准备好的

            编写连接池,实现一个接口DataSource

    开源数据源实现

    • DBCP
    • C3P0
    • Druid:阿里巴巴

            使用了这些数据库连接池之后,我们在项目开发中就不需要编写连接数据库的代码了

    DBCP

      需要用到的jar包

    • commons-dbcp-1.4
    • commons-pool-1.6

            配置文件dbcp.properties

    1. #连接设置
    2. driverClassName=com.mysql.jdbc.Driver
    3. url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false
    4. username=root
    5. password=123456
    6. #初始化连接
    7. initialSize=10
    8. #最大连接数量
    9. maxActive=50
    10. #最大空闲连接
    11. maxIdle=20
    12. #最小空闲连接
    13. minIdle=5
    14. #超时等待时间以毫秒为单位 6000毫秒/1000等于60
    15. maxWait=60000
    16. #JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:【属性名=property;】
    17. #注意:user 与 password 两个属性会被明确地传递,因此这里不需要包含他们。
    18. connectionProperties=useUnicode=true;characterEncoding=UTF8
    19. #指定由连接池所创建的连接的自动提交(auto-commit)状态。
    20. defaultAutoCommit=true
    21. #driver default 指定由连接池所创建的连接的只读(read-only)状态。
    22. #如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
    23. defaultReadOnly=
    24. #driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
    25. #可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
    26. defaultTransactionIsolation=READ_COMMITTED

            工具类

    1. import org.apache.commons.dbcp.BasicDataSourceFactory;
    2. import javax.sql.DataSource;
    3. import java.io.InputStream;
    4. import java.sql.*;
    5. import java.util.Properties;
    6. public class JdbcUtils_DBCP {
    7. private static DataSource dataSource = null;
    8. static {
    9. try {
    10. InputStream in = JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcp.properties");
    11. Properties properties = new Properties();
    12. properties.load(in);
    13. //创建数据源 工厂模式--->创建对象
    14. dataSource = BasicDataSourceFactory.createDataSource(properties);
    15. } catch (Exception e) {
    16. e.printStackTrace();
    17. }
    18. }
    19. /**
    20. * 获取连接
    21. */
    22. public static Connection getConnection() throws SQLException {
    23. return dataSource.getConnection(); //从数据源中获取连接
    24. }
    25. /**
    26. * 释放资源
    27. */
    28. public static void release(Connection con, Statement st, ResultSet rs) {
    29. if (rs != null) {
    30. try {
    31. rs.close();
    32. } catch (SQLException e) {
    33. e.printStackTrace();
    34. }
    35. }
    36. if (st != null) {
    37. try {
    38. st.close();
    39. } catch (SQLException e) {
    40. e.printStackTrace();
    41. }
    42. }
    43. if (con != null) {
    44. try {
    45. con.close();
    46. } catch (SQLException e) {
    47. e.printStackTrace();
    48. }
    49. }
    50. }
    51. }

            测试类

    1. import com.yuan.lesson02.utils.JdbcUtils;
    2. import java.sql.Connection;
    3. import java.sql.PreparedStatement;
    4. import java.sql.SQLException;
    5. public class TestDBCP {
    6. public static void main(String[] args) {
    7. Connection connection = null;
    8. PreparedStatement preparedStatement = null;
    9. try {
    10. connection = JdbcUtils.getConnection();
    11. // PreparedStatement 与 Statement 的区别
    12. //使用 ? 占位符替代
    13. String sql = "INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`) VALUES (?,?,?,?,?)";//预编译,SQL,先写SQL,然后不执行
    14. preparedStatement = connection.prepareStatement(sql);
    15. //手动给参数赋值
    16. preparedStatement.setInt(1, 4);
    17. preparedStatement.setString(2, "牛六");
    18. preparedStatement.setString(3, "123456");
    19. preparedStatement.setString(4, "niuliu@sina.com");
    20. preparedStatement.setDate(5, new java.sql.Date(new java.util.Date().getTime()));
    21. int num = preparedStatement.executeUpdate();
    22. if (num > 0) {
    23. System.out.println("插入成功!");
    24. }
    25. } catch (SQLException e) {
    26. e.printStackTrace();
    27. } finally {
    28. JdbcUtils.release(connection, preparedStatement, null);
    29. }
    30. }
    31. }


    C3P0

      需要用到的jar包

    • c3p0-0.9.5.5.jar
    • mchange-commons-java-0.2.19.jar

            配置文件c3p0-config.xml

    1. "1.0" encoding="UTF-8"?>
    2. <default-config>
    3. "driverClass">com.mysql.jdbc.Driver
    4. "jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    5. "user">root
    6. "password">123456
    7. "acquiredIncrement">5
    8. "initialPoolSize">10
    9. "minPoolSize">5
    10. "maxPoolSize">20
    11. default-config>
    12. "MySQL">
    13. "driverClass">com.mysql.jdbc.Driver
    14. "jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC
    15. "user">root
    16. "password">123456
    17. "acquiredIncrement">5
    18. "initialPoolSize">10
    19. "minPoolSize">5
    20. "maxPoolSize">20

            工具类

    1. import com.mchange.v2.c3p0.ComboPooledDataSource;
    2. import org.apache.commons.dbcp.BasicDataSourceFactory;
    3. import javax.sql.DataSource;
    4. import java.io.InputStream;
    5. import java.sql.Connection;
    6. import java.sql.ResultSet;
    7. import java.sql.SQLException;
    8. import java.sql.Statement;
    9. import java.util.Properties;
    10. public class JdbcUtils_C3P0 {
    11. private static ComboPooledDataSource comboPooledDataSource = null;
    12. static {
    13. try {
    14. //代码版配置
    15. // comboPooledDataSource = new ComboPooledDataSource();
    16. // comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
    17. // comboPooledDataSource.setUser("root");
    18. // comboPooledDataSource.setPassword("123456");
    19. // comboPooledDataSource.setJdbcUrl("jdbc:mysql://localhost:3306/jdbcstudy");
    20. // comboPooledDataSource.setInitialPoolSize(5);
    21. // comboPooledDataSource.setMaxPoolSize(10);
    22. // comboPooledDataSource.setMinPoolSize(5);
    23. //创建数据源 工厂模式--->创建对象
    24. comboPooledDataSource = new ComboPooledDataSource("MySQL"); //配置文件写法
    25. } catch (Exception e) {
    26. e.printStackTrace();
    27. }
    28. }
    29. /**
    30. * 获取连接
    31. */
    32. public static Connection getConnection() throws SQLException {
    33. return comboPooledDataSource.getConnection(); //从数据源中获取连接
    34. }
    35. /**
    36. * 释放资源
    37. */
    38. public static void release(Connection con, Statement st, ResultSet rs) {
    39. if (rs != null) {
    40. try {
    41. rs.close();
    42. } catch (SQLException e) {
    43. e.printStackTrace();
    44. }
    45. }
    46. if (st != null) {
    47. try {
    48. st.close();
    49. } catch (SQLException e) {
    50. e.printStackTrace();
    51. }
    52. }
    53. if (con != null) {
    54. try {
    55. con.close();
    56. } catch (SQLException e) {
    57. e.printStackTrace();
    58. }
    59. }
    60. }
    61. }

            测试类

    1. public class TestC3P0 {
    2. public static void main(String[] args) {
    3. Connection connection = null;
    4. PreparedStatement preparedStatement = null;
    5. try {
    6. connection = JdbcUtils_C3P0.getConnection();
    7. // PreparedStatement 与 Statement 的区别
    8. //使用 ? 占位符替代
    9. String sql = "INSERT INTO users(`id`,`name`,`password`,`email`,`birthday`) VALUES (?,?,?,?,?)";//预编译,SQL,先写SQL,然后不执行
    10. preparedStatement = connection.prepareStatement(sql);
    11. //手动给参数赋值
    12. preparedStatement.setInt(1, 6);
    13. preparedStatement.setString(2, "牛六");
    14. preparedStatement.setString(3, "123456");
    15. preparedStatement.setString(4, "niuliu@sina.com");
    16. preparedStatement.setDate(5, new java.sql.Date(new java.util.Date().getTime()));
    17. int num = preparedStatement.executeUpdate();
    18. if (num > 0) {
    19. System.out.println("插入成功!");
    20. }
    21. } catch (SQLException e) {
    22. e.printStackTrace();
    23. } finally {
    24. JdbcUtils.release(connection, preparedStatement, null);
    25. }
    26. }
    27. }

    小结:

            无论用什么数据源,本质还是一样的,DataSource接口不会变,方法就不会变。

  • 相关阅读:
    [go]文件与目录操作
    线性矩阵不等式(LMI)在控制理论中的应用
    开源在物联网(IoT)中的应用
    360 G800行车记录仪,不使用降压线如何开机,8芯插头的定义。
    Python多线程方案
    医疗实施-MDM主数据管理基本介绍
    【ElM分类】基于麻雀搜索算法优化ElM神经网络实现数据分类附代码
    《上海市交通领域科技创新发展行动计划》发布
    责任链模式
    Dart(11)-mixin
  • 原文地址:https://blog.csdn.net/weixin_48426115/article/details/126299933