27.4 数据库连接池、C3P0连接池、Druid连接池、Spring框架使用JDBC

目录

1 数据库连接池

2 C3P0数据库连接池技术

2.1 导包:

2.2 导入c3p0-config.xml配置文件

2.3 测试是否连接成功

3 Druid数据库连接池技术

3.1 导包:

3.2 定义druid.properties配置文件

3.3 测试是否连接成功

2.4 列:使用jdbc工具类实现Druid连接池技术,给表中添加数据

4 Spring框架使用JDBC

4.1. 导入jar包

4.2 书写代码


1 数据库连接池

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

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

使用数据库连接池的好处:1. 节约资源    2. 用户访问高效

2 C3P0数据库连接池技术

2.1 导包:

  • 导入数据库驱动jar包:mysql-connector-java-5.1.37-bin.jar
  • 导入层c3p0包:c3p0-0.9.5.2.jar    mchange-commons-java-0.2.12.jar

2.2 导入c3p0-config.xml配置文件

<c3p0-config>
  <!-- 使用默认的配置读取连接池对象 -->
  <default-config>
  	<!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db3</property>
    <property name="user">root</property>
    <property name="password">123</property>
    
    <!-- 连接池参数 -->
    <!--初始化申请的连接数量-->
    <property name="initialPoolSize">5</property>
    <!--最大的连接数量-->
    <property name="maxPoolSize">10</property>
    <!--超时时间-->
    <property name="checkoutTimeout">3000</property>
  </default-config>

  <named-config name="otherc3p0"> 
    <!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db3</property>
    <property name="user">root</property>
    <property name="password">123</property>
    
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">8</property>
    <property name="checkoutTimeout">1000</property>
  </named-config>
</c3p0-config>

2.3 测试是否连接成功

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * c3p0演示
 */
public class c3p0Demo02 {
    public static void main(String[] args) throws SQLException {
        method01();
        System.out.println("==================");
       // method02();
    }

    public static void method01() throws SQLException {
        //1.创建数据库连接池对象
        DataSource dataSource = new ComboPooledDataSource();
        //2 从连接池中获取连接对象
        for (int i = 1; i <= 10; i++) {
            Connection connection = dataSource.getConnection();
            System.out.println(i + "\t" + connection);
        }
    }
    public static void method02() throws SQLException {
        DataSource dataSource=new ComboPooledDataSource("otherc3p0");
            for (int i = 1; i <= 10; i++) {
                Connection connection = dataSource.getConnection();
                System.out.println(i+"\t"+connection);
            }
    }
}

 

3 Druid数据库连接池技术

3.1 导包:

  • 导入数据库驱动jar包:mysql-connector-java-5.1.37-bin.jar
  • 导入层Druid包:druid-1.0.9.jar

3.2 定义druid.properties配置文件

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db3
username=root
password=123
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大等待时间
maxWait=3000

3.3 测试是否连接成功

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;

public class DruidDemo {
    public static void main(String[] args) throws Exception {
        //1.导入jar包  druid-1.0.9.jar  mysql-connector-java-5.1.37-bin.jar
        //2.定义配置文件   druid.properties
        //3.加载配置文件
        Properties properties = new Properties();
        ClassLoader classLoader = DruidDemo.class.getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("druid.properties");
        properties.load(inputStream);
        //4.获取连接池对象:通过工厂来来获取  DruidDataSourceFactory
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        //5.获取连接
        Connection connection = dataSource.getConnection();
        System.out.println(connection);

    }
}

2.4 列:使用jdbc工具类实现Druid连接池技术,给表中添加数据

创建jdbc工具类

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;

/**
 * Druid连接池的工具类
 */
public class JDBCUtils {
    //1 定义成员变量DataSource
    private static DataSource dataSource;

    static {
        try {
            //1 加载配置文件
            Properties properties = new Properties();
            properties.load(JDBCUtils.class.getClassLoader().
                    getResourceAsStream("druid.properties"));
            //2 获取DataSource
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    /**
     * 获取连接池方法
     */
    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 释放资源
     */
    public static void close(Statement statement, Connection connection) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static void close(Statement statement, Connection connection, ResultSet resultSet) {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        close(statement, connection);
    }
}

表添加数据

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

/**
 * 使用DruidUtils工具类
 */
public class DruidDemo02 {
    public static void main(String[] args) {
        /*
         * 完成添加操作:给account表添加一条记录
         */
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        try {
            //1 获取连接
                connection= JDBCUtils.getConnection() ;
                //2 定义sql语句
            String sql="insert into account values(null,?,?)";
            //3 获取连接对象
            preparedStatement=connection.prepareStatement(sql);
            //4.给?赋值
            preparedStatement.setString(1,"laoli");
            preparedStatement.setDouble(2,3000);
            //5 执行sql
            int i = preparedStatement.executeUpdate();
            System.out.println(i);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
            JDBCUtils.close(preparedStatement,connection);
        }
    }
}

4 Spring框架使用JDBC

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

4.1. 导入jar包

  • 导入数据库驱动jar包:mysql-connector-java-5.1.37-bin.jar
  • 导入层spring包:
                commons-logging-1.2.jar
                spring-beans-5.0.0.RELEASE.jar
                spring-core-5.0.0.RELEASE.jar
                spring-jdbc-5.0.0.RELEASE.jar
                spring-tx-5.0.0.RELEASE.jar

4.2 书写代码

创建员工表的Javabean对象

import com.util.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

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

public class JdbcTempleDemo01 {
    /*1 导入jar包: commons-logging-1.2.jar
                spring-beans-5.0.0.RELEASE.jar
                spring-core-5.0.0.RELEASE.jar
                spring-jdbc-5.0.0.RELEASE.jar
                spring-tx-5.0.0.RELEASE.jar      */
    //1 获取JdbcTemle对象
    private JdbcTemplate jdbcTemplate=new JdbcTemplate(JDBCUtils.getDataSource());

    /**
     * 1. 修改1001号数据的 salary 为 10000
     */
    @Test
    public void test1(){
        //2 定义sql语句
        String sql="update emp set salary=10000 where id=1001";
        //3 执行sql
        int count = jdbcTemplate.update(sql);
        System.out.println(count);
    }
    /**
     * 2. 添加一条记录
     */
    @Test
    public void test2(){
        String sql="insert into emp(id,ename,dept_id) value (?,?,?)";
        int c = jdbcTemplate.update(sql, 1018, "laowang", 10);
        System.out.println(c);
    }
    /**
     * 3.删除刚才添加的记录
     */
    @Test
    public void test3(){
        String sql="delete from emp where id=?";
        int c = jdbcTemplate.update(sql,1015);
        System.out.println(c);
    }

    /**
     * 4.查询id为1001的记录,将其封装为Map集合
     * 注意:这个方法查询的结果集长度只能是1
     */
    @Test
    public void test4(){
        String sql="select * from emp where id=? ";
        Map<String, Object> map = jdbcTemplate.queryForMap(sql, 1001);
        System.out.println(map);
    }
    /**
     * 5. 查询所有记录,将其封装为List
     */
    @Test
    public void  test5(){
        String sql="select * from emp";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        for (Map<String, Object> map : maps) {
            System.out.println(map);
        }
    }


    /**
     * 6. 查询所有记录,将其封装为Emp对象的List集合
     */
    @Test
    public void test6(){
        String sql="select * from emp";
        List<Emp> list = jdbcTemplate.query(sql, new RowMapper<Emp>() {
            @Override
            public Emp mapRow(ResultSet resultSet, int i) throws SQLException {
                int id = resultSet.getInt("id");
                String ename = resultSet.getString("ename");
                int job_id = resultSet.getInt("job_id");
                int mgr = resultSet.getInt("mgr");
                Date joindate = resultSet.getDate("joindate");
                double salary = resultSet.getDouble("salary");
                double bonus = resultSet.getDouble("bonus");
                int dept_id = resultSet.getInt("dept_id");
                Emp emp = new Emp(id, ename, job_id, mgr, joindate, salary, bonus, dept_id);
                return emp;
            }
        });
        for (Emp emp : list) {
            System.out.println(emp);
        }
    }

    /**
     * 6. 查询所有记录,将其封装为Emp对象的List集合
     */
    @Test
    public  void test6_2(){
        String sql="select * from emp";
        List<Emp> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Emp.class));
        for (Emp emp : list) {
            System.out.println(emp);
        }
    }

    /**
     * 7. 查询总记录数
     */
    @Test
    public void test7(){
        String sql="select count(id) from emp";
        Long total = jdbcTemplate.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、付费专栏及课程。

余额充值