• Java——JDBC连接池(c3p0、druid连接池及JDBCTemplate模版)


    目录

    1、连接池

    1.1、什么是连接池?

    1.2、连接池的好处

    1.3、连接池的实现

    1.4、厂商实现

    1.5、相关jar包

    2、C3P0连接池技术

    2.1、实现步骤

    2.2、代码实现

    3、Druid连接池技术

    3.1、实现步骤

    3.2、代码实现

    4、JDBCTemplate模版

    4.1、实现步骤


     

    1、连接池

    1.1、什么是连接池?

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

    1.2、连接池的好处

    1、节约资源。

    2、减少连接数据库的次数。

    3、用户访问高效。

    1.3、连接池的实现

    标准接口:DataSource   javax.sql包下的
    获取连接:getConnection()
    归还连接:Connection.close()。如果连接对象Connection是从连接池中获取的,那么调用Connection.close()方法,则不会再关闭连接了。而是归还连接

    1.4、厂商实现

     一般我们不去实现它,有数据库厂商来实现
    1、C3P0:数据库连接池技术。
    2、Druid:数据库连接池实现技术,由阿里巴巴提供的。

    1.5、相关jar包

    链接:https://pan.baidu.com/s/1Qo5BEjeGa4ikuxTetiiY5A 
    提取码:mlni

    2、C3P0连接池技术

    2.1、实现步骤

    1、新建web工程。

    2、导入出c3p0的jar包,以及mysql驱动包。   

    3、定义配置文件c3p0-config.xml,直接将文件放在src目录下即可。

    4、获取连接:getConnection。

    创建数据库

    注意:这里我方便用的是之前事务里面的表,也可以自习创建表进行填写数据进行测试。 

    1. CREATE TABLE `account` (
    2. `name` varchar(20) NOT NULL,
    3. `money` int(255) DEFAULT NULL,
    4. PRIMARY KEY (`name`)
    5. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

     

    导入jar包

      

    2.2、代码实现

    把配置文件c3p0-config.xml放入src目录下

    注意:配置文件中的数据库表名和密码自习修改。

    1. "1.0" encoding="UTF-8"?>
    2. <c3p0-config>
    3. <default-config>
    4. <property name="driverClass">com.mysql.jdbc.Driverproperty>
    5. <property name="jdbcUrl">jdbc:mysql://localhost:3306/test6property>
    6. <property name="user">rootproperty>
    7. <property name="password">xxxproperty>
    8. <property name="initialPoolSize">5property>
    9. <property name="maxPoolSize">10property>
    10. <property name="checkoutTimeout">3000property>
    11. default-config>
    12. c3p0-config>

    新建c3p0Util工具类 

    c3p0Util工具类

    1. public class c3p0Util {
    2. //默认加载src 下面c3p0-config.xml加载
    3. private static ComboPooledDataSource ds = new ComboPooledDataSource();
    4. //创建连接
    5. public static Connection getConnection() {
    6. Connection conn = null;
    7. try {
    8. conn = ds.getConnection();
    9. } catch (SQLException e) {
    10. e.printStackTrace();
    11. }
    12. return conn;
    13. }
    14. //关闭方法
    15. public static void close(ResultSet rs, Statement stmt, Connection conn) {
    16. try {
    17. if (rs != null) {
    18. rs.close();
    19. rs = null;
    20. }
    21. } catch (SQLException e) {
    22. e.printStackTrace();
    23. }
    24. try {
    25. if (stmt != null) {
    26. stmt.close();
    27. stmt = null;
    28. }
    29. } catch (SQLException e) {
    30. e.printStackTrace();
    31. }
    32. try {
    33. if (conn != null) {
    34. conn.close();
    35. conn = null;
    36. }
    37. } catch (SQLException e) {
    38. e.printStackTrace();
    39. }
    40. }
    41. public void close(Statement stmt, Connection conn) {
    42. try {
    43. if (stmt != null) {
    44. stmt.close();
    45. stmt = null;
    46. }
    47. } catch (SQLException e) {
    48. e.printStackTrace();
    49. }
    50. try {
    51. if (conn != null) {
    52. conn.close();
    53. conn = null;
    54. }
    55. } catch (SQLException e) {
    56. e.printStackTrace();
    57. }
    58. }
    59. }

    新建test包,创建c3p0Test类进行测试 

    c3p0Test类

    1. public class c3p0Test {
    2. @Test
    3. public void test1() {
    4. Connection conn = c3p0Util.getConnection();
    5. PreparedStatement pstmt = null;
    6. ResultSet rs = null;
    7. try {
    8. pstmt = conn.prepareStatement("select * from account");
    9. rs = pstmt.executeQuery();
    10. while (rs.next()) {
    11. String name = rs.getString("name");
    12. int money = rs.getInt("money");
    13. System.out.println(name + ":" + money);
    14. }
    15. } catch (SQLException e) {
    16. e.printStackTrace();
    17. } finally {
    18. c3p0Util.close(rs, pstmt, conn);
    19. }
    20. }
    21. }

    3、Druid连接池技术

    3.1、实现步骤

    1、 导入jar包 druid-1.0.9.jar。

    2、 定义配置文件:是xx.properties形式的,可以叫任意名称,可以放在任意目录下, 一般都放在src。
    3、加载配置文件Properties。
    4、获取数据库连接池对象:通过工厂来来获取  DruidDataSourceFactory。
    5、 获取连接:getConnection。

    导入jar包 

     

    3.2、代码实现

    导入druid.properties配置文件到src目录

    1. driverClassName=com.mysql.jdbc.Driver
    2. url=jdbc:mysql:///test6
    3. username=root
    4. password=ssl0528
    5. # 初始化连接数量
    6. initialSize=5
    7. # 最大连接数
    8. maxActive=10
    9. # 最大等待时间
    10. maxWait=3000

    druidUtil类 

    1. public class druidUtil {
    2. //定义成员变量 DataSource ds
    3. private static DataSource dataSource;
    4. static {
    5. Properties pro = new Properties();
    6. InputStream is = null;
    7. try {
    8. //通过反射读取配置文件
    9. is = druidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
    10. pro.load(is);
    11. dataSource= DruidDataSourceFactory.createDataSource(pro);
    12. } catch (IOException e) {
    13. e.printStackTrace();
    14. } catch (Exception e) {
    15. e.printStackTrace();
    16. }finally {
    17. try {
    18. is.close();
    19. } catch (IOException e) {
    20. e.printStackTrace();
    21. }
    22. }
    23. }
    24. //获取连接
    25. public static Connection getConnection(){
    26. Connection conn = null;
    27. try {
    28. conn = dataSource.getConnection();
    29. } catch (SQLException e) {
    30. e.printStackTrace();
    31. }
    32. return conn;
    33. }
    34. //获取DataSource对象 给JDBCTemplate提供
    35. public static DataSource getDataSource(){
    36. return dataSource;
    37. }
    38. //关闭方法
    39. public static void close(ResultSet rs, Statement stmt,Connection conn){
    40. try {
    41. if(rs != null){
    42. rs.close();
    43. rs =null;//关闭连接,给赋值null,gc垃圾回收回机制会优先处理这些对象
    44. }
    45. } catch (SQLException e) {
    46. e.printStackTrace();
    47. }
    48. try {
    49. if(stmt != null){
    50. stmt.close();
    51. stmt=null;
    52. }
    53. } catch (SQLException e) {
    54. e.printStackTrace();
    55. }
    56. try {
    57. if(conn != null){
    58. conn.close();
    59. conn = null;
    60. }
    61. } catch (SQLException e) {
    62. e.printStackTrace();
    63. }
    64. }
    65. public static void close(Statement stmt,Connection conn){
    66. try {
    67. if(stmt != null){
    68. stmt.close();
    69. stmt=null;
    70. }
    71. } catch (SQLException e) {
    72. e.printStackTrace();
    73. }
    74. try {
    75. if(conn != null){
    76. conn.close();
    77. conn = null;
    78. }
    79. } catch (SQLException e) {
    80. e.printStackTrace();
    81. }
    82. }
    83. }

    druidTest类测试 

    1. public class druidTest {
    2. @Test
    3. public void test1() {
    4. Connection conn = druidUtil.getConnection();
    5. PreparedStatement pstmt = null;
    6. ResultSet rs = null;
    7. try {
    8. pstmt = conn.prepareStatement("select * from account");
    9. rs = pstmt.executeQuery();
    10. while (rs.next()) {
    11. String name = rs.getString("name");
    12. int money = rs.getInt("money");
    13. System.out.println(name + ":" + money);
    14. }
    15. } catch (SQLException e) {
    16. e.printStackTrace();
    17. } finally {
    18. druidUtil.close(rs, pstmt, conn);
    19. }
    20. }
    21. }

    4、JDBCTemplate模版

    JDBCTemplate模版就是JDBC的一个框架,该框架及其方便,减少了大量的代码就能实现连接数据库。Spring JDBC,Spring框架对JDBC的简单封装。

    1、创建数据库表user

    1. CREATE TABLE `user` (
    2. `id` int(11) NOT NULL AUTO_INCREMENT,
    3. `name` varchar(255) DEFAULT NULL,
    4. `age` int(11) DEFAULT NULL,
    5. PRIMARY KEY (`id`)
    6. ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

    自行添加数据 

     

    2、创建实体类

     

     User实体类

    1. public class User {
    2. private int id;
    3. private String name;
    4. private int age;
    5. public User() {
    6. }
    7. public User(int id, String name, int age) {
    8. this.id = id;
    9. this.name = name;
    10. this.age = age;
    11. }
    12. public int getId() {
    13. return id;
    14. }
    15. public void setId(int id) {
    16. this.id = id;
    17. }
    18. public String getName() {
    19. return name;
    20. }
    21. public void setName(String name) {
    22. this.name = name;
    23. }
    24. public int getAge() {
    25. return age;
    26. }
    27. public void setAge(int age) {
    28. this.age = age;
    29. }
    30. @Override
    31. public String toString() {
    32. return "User{" +
    33. "id=" + id +
    34. ", name='" + name + '\'' +
    35. ", age=" + age +
    36. '}';
    37. }
    38. }

    4.1、实现步骤

    1. 导入jar包 4 + 1

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

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

     

    创建一个template包,里面创建一个templateTest测试类 

     

    1. public class templateTest {
    2. private JdbcTemplate template = new JdbcTemplate(druidUtil.getDataSource());
    3. @Test
    4. public void save() {
    5. int i = template.update("insert into user(name,age) value('zhaoliu',27)");
    6. System.out.println(i);
    7. }
    8. @Test
    9. public void delete() {
    10. String sql = "delete from user where id=?";
    11. int i = template.update(sql, 3);
    12. System.out.println(i);
    13. }
    14. @Test
    15. public void update() {
    16. String sql = "update user set name='xiaomi',age=18 where id=?";
    17. int i = template.update(sql, 2);
    18. System.out.println(i);
    19. }
    20. //查询数据返回list
    21. public List query_list() {
    22. String sql = "select * from user";
    23. List query = template.query(sql, new BeanPropertyRowMapper<>(User.class));
    24. return query;
    25. }
    26. @Test
    27. public void test1() {
    28. List list = query_list();
    29. for (User user : list) {
    30. System.out.println(user.getId());
    31. System.out.println(user.getName());
    32. System.out.println(user.getAge());
    33. }
    34. }
    35. //查询条数
    36. public Integer query_count(){
    37. String sql="select count(*) from user";
    38. Integer i = template.queryForObject(sql, Integer.class);
    39. return i;
    40. }
    41. @Test
    42. public void test2(){
    43. Integer i = query_count();
    44. System.out.println(i);
    45. }
    46. //查询数据返回map
    47. @Test
    48. public void query_map(){
    49. String sql="select * from user where id=?";
    50. Map stringObjectMap = template.queryForMap(sql,1);
    51. Set set = stringObjectMap.keySet();
    52. for (String s : set) {
    53. Object o = stringObjectMap.get(s);
    54. System.out.println(s+":"+o);
    55. }
    56. }
    57. }
  • 相关阅读:
    python进阶(28)import导入机制原理
    JSTL标准标签库 EL表达式
    LeetCode75——Day4
    【深度学习】【Prompt】使用GPT的一些提示词
    技巧 | 如何解决 zsh: permission denied 问题 | Mac
    家政服务小程序,家政预约小程序,家政服务预约小程序源码
    Intel汇编-CALL调用
    Redis之Redis 6.0中Hash(ziplist)解读
    活动报名|9月24日 Apache Flink Meetup · 北京站,Flink 1.16 新版本发布!
    MySQL 索引测试
  • 原文地址:https://blog.csdn.net/select_myname/article/details/126807350