脚本宝典收集整理的这篇文章主要介绍了数据库连接池&DBUtils,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
1) 什么是连接池
2) 连接池的好处
Java为数据库连接池提供了公共的接口:javax.SQL.DataSource,各个厂商需要让自己的连接池实现这个接口。这样应用程序可以方便的切换不同厂商的连接池!
常见的连接池有 DBCP连接池, C3P0连接池, Druid连接池, 接下里我们就详细学习一下
#创建数据库 CREATE DATABASE db5 CHARACTER SET utf8; #使用数据库 USE db5; #创建员工表 CREATE TABLE employee ( eid INT Primary KEY AUTO_INCREMENT , ename VArchAR (20), -- 员工姓名 age INT , -- 员工年龄 sex VARCHAR (6), -- 员工性别 salary DOubLE , -- 薪水 empdate DATE -- 入职日期 ); #插入数据 INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'李清 照',22,'女',4000,'2018-11-12'); INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'林黛 玉',20,'女',5000,'2019-03-14'); INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'杜 甫',40,'男',6000,'2020-01-01'); INSERT INTO employee (eid, ename, age, sex, salary, empdate) VALUES(NULL,'李白',25,'男',3000,'2017-10-01');
DBCP也是一个开源的连接池,是apache成员之一,在企业开发中也比较常见,tomcat内置的连接池。
1.5.1 创建项目 导入 jar包
1)将这两个 jar包添加到 myJar文件夹中 (jar包在资料里的软件文件夹中)
2) 添加myJar库 到项目的依赖中
代码示例
public class DBCPUtils { //1.定义常量 保存数据库连接的相关信息 public static final String DRIVERNAME = "com.MySQL.jdbc.Driver"; public static final String URL = "jdbc:mysql://localhost:3306/db5?characterEncoding=UTF-8"; public static final String USERNAME = "root"; public static final String PASSWORD = "123456"; //2.创建连接池对象 (有DBCP提供的实现类) public static BasicDataSource dataSource = new BasicDataSource(); //3.使用静态代码块进行配置 static{ dataSource.setDriverclassname(DRIVERNAME); dataSource.setUrl(URL); dataSource.setUsername(USERNAME); dataSource.setPassword(PASSWORD); } //4.获取连接的方法 public static Connection getConnection() throws SQLException { //从连接池中获取连接 Connection connection = dataSource.getConnection(); return connection; } //5.释放资源方法 public static void close(Connection con, Statement statement){ if(con != null && statement != null){ try { statement.close(); //归还连接 con.close(); } catch (SQLException e) { e.PRintStackTrace(); } } } public static void close(Connection con, Statement statement, ResultSet resultSet){ if(con != null && statement != null && resultSet != null){ try { resultSet.close(); statement.close(); //归还连接 con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
需求: 查询所有员工的姓名
public class testDBCP { /* * 测试DBCP连接池 * */ public static void main(String[] args) throws SQLException { //1.从DBCP连接池中拿到连接 Connection con = DBCPUtils.getConnection(); //2.获取Statement对象 Statement statement = con.createStatement(); //3.查询所有员工的姓名 String sql = "select ename From employee"; ResultSet resultSet = statement.executeQuery(sql); //4.处理结果集 while(resultSet.next()){ String ename = resultSet.getString("ename"); System.out.println("员工姓名: " + ename); } //5.释放资源 DBCPUtils.close(con,statement,resultSet); } }
C3P0是一个开源的JDBC连接池,支持JDBC3规范和JDBC2的标准扩展。目前使用它的开源项目有Hibernate、Spring等。
1) 将jar包 复制到myJar文件夹即可,IDEA会自动导入
<@H_357_512@c3p0-config> <!--默认配置--> <default-config> <proPErty name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/db5?characterEncoding=UTF-8</property> <property name="user">root</property> <property name="password">123456</property> <!-- inITialPoolSize:初始化时获取三个连接, 取值应在minPoolSize与maxpoolSize之间。 --> <property name="initialPoolSize">3</property> <!-- maxidleTime:最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。--> <property name="maxIdleTime">60</property> <!-- maxPoolSize:连接池中保留的最大连接数 --> <property name="maxPoolSize">100</property> <!-- minPoolSize: 连接池中保留的最小连接数 --> <property name="minPoolSize">10</property> </default-config> <!--配置连接池mysql--> <named-config name="mysql"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/db5</property> <property name="user">root</property> <property name="password">123456</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> </named-config> <!--配置连接池2,可以配置多个--> </c3p0-config>
3) 在项目下创建一个resource文件夹(专门存放资源文件)
4) 选择文件夹,右键 将resource文件夹指定为资源文件夹
5) 将文件放在resource目录下即可,创建连接池对象的时候会去加载这个配置文件
public class C3P0Utils { //1.创建连接池对象 C3P0对DataSource接口的实现类 //使用的配置是 配置文件中的默认配置 //public static ComboPooledDataSource dataSource = new ComboPooledDataSource(); //使用指定的配置 public static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); //获取连接的方法 public static Connection getConnection() throws SQLException { return dataSource.getConnection(); } //释放资源 public static void close(Connection con, Statement statement){ if(con != null && statement != null){ try { statement.close(); //归还连接 con.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(Connection con, Statement statement, ResultSet resultSet){ if(con != null && statement != null && resultSet != null){ try { resultSet.close(); statement.close(); //归还连接 con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
需求: 查询姓名为 李白的员工信息
public class TestC3P0 { //需求 查询姓名为李白的 记录 public static void main(String[] args) throws SQLException { //1.获取连接 Connection con = C3P0Utils.getConnection(); //2.获取预处理对象 String sql = "select * from employee where ename = ?"; Preparedstatement ps = con.prepareStatement(sql); //3.设置占位符的值 ps.setString(1,"李白"); ResultSet resultSet = ps.executeQuery(); //4.处理结果集 while(resultSet.next()){ int eid = resultSet.getInt("eid"); String ename = resultSet.getString("ename"); int age = resultSet.getInt("age"); String sex = resultSet.getString("sex"); double salary = resultSet.getDouble("salary"); Date date = resultSet.getDate("empdate"); System.out.println(eid +" " + ename + " " + age +" " + sex +" " + salary +" " +date); } //5.释放资源 C3P0Utils.close(con,ps,resultSet); } }
1.6.4 常见配置
Druid(德鲁伊)是阿里巴巴开发的号称为监控而生的数据库连接池,Druid是目前最好的数据库连接池。在功能、性能、扩展性方面,都超过其他数据库连接池,同时加入了日志监控,可以很好的监控DB池连接和SQL的执行情况。
1) 导入 jar包
2) 导入配置文件
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/db5?characterEncoding=UTF-8 username=root password=123456 initialSize=5 maxActive=10 maxWait=3000
public class DruidUtils { //1.定义成员变量 public static DataSource dataSource; //2.静态代码块 static{ try { //3.创建属性集对象 Properties p = new Properties(); //4.加载配置文件 Druid 连接池不能够主动加载配置文件 ,需要指定文件 InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"); //5. 使用Properties对象的 load方法 从字节流中读取配置信息 p.load(inputStream); //6. 通过工厂类获取连接池对象 dataSource = DruidDataSourceFactory.createDataSource(p); } catch (Exception e) { e.printStackTrace(); } } //获取连接的方法 public static Connection getConnection(){ try { return dataSource.getConnection(); } catch (SQLException e) { e.printStackTrace(); return null; } } //释放资源 public static void close(Connection con, Statement statement){ if(con != null && statement != null){ try { statement.close(); //归还连接 con.close(); } catch (SQLException e) { e.printStackTrace(); } } } public static void close(Connection con, Statement statement, ResultSet resultSet){ if(con != null && statement != null && resultSet != null){ try { resultSet.close(); statement.close(); //归还连接 con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
需求: 查询薪资在3000 - 5000元之间的员工姓名
public class TestDruid { // 需求 查询 薪资在3000 到 5000之间的员工的姓名 public static void main(String[] args) throws SQLException { //1.获取连接 Connection con = DruidUtils.getConnection(); //2.获取Statement对象 Statement statement = con.createStatement(); //3.执行查询 ResultSet resultSet = statement.executeQuery("select ename from employee where salary between 3000 and 5000"); //4.处理结果集 while(resultSet.next()){ String ename = resultSet.getString("ename"); System.out.println(ename); } //5.释放资源 DruidUtils.close(con,statement,resultSet); } }
使用JDBC我们发现冗余的代码太多了,为了简化开发 我们选择使用 DbUtils
Commons DbUtils是Apache组织提供的一个对JDBC进行简单封装的开源工具类库,使用它能够简化JDBC应用程序的开发,同时也不会影响程序的性能。
1) JavaBean 就是一个类, 开发中通常用于封装数据,有一下特点
2) 创建Employee类和数据库的employee表对应
public class Employee implements Serializable { private int eid; private String ename; private int age; private String sex; private double salary; private Date empdate; //空参 getter setter省略 }
//手动方式 创建QueryRunner对象 QueryRunner qr = new QueryRunner();
//自动创建 传入数据库连接池对象 QueryRunner qr2 = new QueryRunner(DruidUtils.getDataSource());
//获取连接池对象 public static DataSource getDataSource(){ return dataSource; }
核心方法
update(Connection conn, String sql, Object... params)
步骤
@Test public void testInsert() throws SQLException { //1.创建 QueryRunner 手动模式创建 QueryRunner qr = new QueryRunner(); //2.编写 占位符方式 SQL String sql = "insert into employee values(?,?,?,?,?,?)"; //3.设置占位符的参数 Object[] param = {null,"张百万",20,"女",10000,"1990-12-26"}; //4.执行 update方法 Connection con = DruidUtils.getConnection(); int i = qr.update(con, sql, param); //5.释放资源 DbUtils.closeQuietly(con); }
//修改操作 修改姓名为张百万的员工工资 @Test public void testUpdate() throws SQLException { //1.创建QueryRunner对象 自动模式,传入数据库连接池 QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()); //2.编写SQL String sql = "update employee set salary = ? where ename = ?"; //3.设置占位符参数 Object[] param = {0,"张百万"}; //4.执行update, 不需要传入连接对象 qr.update(sql,param); }
//删除操作 删除id为1 的数据 @Test public void testDelete() throws SQLException { QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()); String sql = "delete from employee where eid = ?"; //只有一个参数,不需要创建数组 qr.update(sql,1); }
本例展示的是使用ResultSetHandler接口的几个常见实现类实现数据库的增删改查,可以大大减少代码量,优化程序。每一种实现类都代表了对查询结果集的一种处理方式
1) 查询id为5的记录,封装到数组中
/* * 查询id为5的记录,封装到数组中 * ArrayHandler 将结果集的第一条数据封装到数组中 * */ @Test public void testFindById() throws SQLException { //1.创建QueryRunner QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()); //2.编写SQL String sql = "select * from employee where eid = ?"; //3.执行查询 Object[] query = qr.query(sql, new ArrayHandler(), 5); //4.获取数据 System.out.println(Arrays.toString(query)); }
2) 查询所有数据,封装到List集合中
/** * 查询所有数据,封装到List集合中 * ArrayListHandler可以将每条数据先封装到数组中, 再将数组封装到集合中 * */ @Test public void testFindAll() throws SQLException { //1.创建QueryRunner QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()); //2.编写SQL String sql = "select * from employee"; //3.执行查询 List<Object[]> query = qr.query(sql, new ArrayListHandler()); //4.遍历集合获取数据 for (Object[] objects : query) { System.out.println(Arrays.toString(objects)); } }
3) 根据ID查询,封装到指定JavaBean中
/** * 查询id为3的记录,封装到指定JavaBean中 * BeanHandler 将结果集的第一条数据封装到 javaBean中 * 4) 查询薪资大于 3000 的所员工信息,封装到JavaBean中再封装到List集合中 5) 查询姓名是 张百万的员工信息,将结果封装到Map集合中 **/ @Test public void testFindByIdJavaBean() throws SQLException { QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()); String sql = "select * from employee where eid = ?"; Employee employee = qr.query(sql, new BeanHandler<Employee>(Employee.class), 3); System.out.println(employee); }
4) 查询薪资大于 3000 的所员工信息,封装到JavaBean中再封装到List集合中
/* * 查询薪资大于 3000 的所员工信息,封装到JavaBean中再封装到List集合中 * BeanListHandler 将结果集的每一条和数据封装到 JavaBean中 再将JavaBean 放到list集合中 * */ @Test public void testFindBySalary() throws SQLException { QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()); String sql = "select * from employee where salary > ?"; List<Employee> list = qr.query(sql, new BeanListHandler<Employee>(Employee.class), 3000); for (Employee employee : list) { System.out.println(employee); } }
5) 查询姓名是 张百万的员工信息,将结果封装到Map集合中
/* * 查询姓名是 张百万的员工信息,将结果封装到Map集合中 * MapHandler 将结果集的第一条记录封装到 Map<String,Object>中 * key对应的是 列名 value对应的是 列的值 * */ @Test public void testFindByName() throws SQLException { QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()); String sql = "select * from employee where ename = ?"; Map<String, Object> map = qr.query(sql, new MapHandler(), "张百万"); Set<map.Entry<String, Object>> entries = map.entrySet(); for (Map.Entry<String, Object> entry : entries) { //打印结果 System.out.println(entry.getKey() +" = " +entry.getValue()); } }
6) 查询所有员工的薪资总额
/* * 查询所有员工的薪资总额 * ScalarHandler 用于封装单个的数据 * */ @Test public void testGetSum() throws SQLException { QueryRunner qr = new QueryRunner(DruidUtils.getDataSource()); String sql = "select sum(salary) from employee"; Double sum = (Double)qr.query(sql, new ScalarHandler<>()); System.out.println("员工薪资总额: " + sum); }
Statement和PreparedStatement都支持批处理操作,这里我们介绍一下PreparedStatement的批处理方式:
1) 要用到的方法
2) mysql 批处理是默认关闭的,所以需要加一个参数才打开mysql 数据库批处理,在url中添加
rewriteBatchedStatements=true 例如: url=jdbc:mysql://127.0.0.1:3306/db5?characterEncoding=UTF-8&rewriteBatchedStatements=true
3) 创建一张表
CREATE TABLE testBatch ( id INT PRIMARY KEY AUTO_INCREMENT, uname VARCHAR(50) )
4) 测试向表中插入 1万条数据
public class TestBatch { //使用批处理,向表中添加 1万条数据 public static void main(String[] args) { try { //1.获取连接 Connection con = DruidUtils.getConnection(); //2.获取预处理对象 String sql ="insert into testBatch(uname) values(?)"; PreparedStatement ps = con.prepareStatement(sql); //3.创建 for循环 来设置占位符参数 for (int i = 0; i < 10000 ; i++) { ps.setString(1,"小强"+i); //将SQL添加到批处理 列表 ps.addBatch(); } //添加时间戳 测试执行效率 long start = System.currentTimeMillis(); //统一 批量执行 ps.executeBatch(); long end = System.currentTimeMillis(); System.out.println("插入10000条数据使用: " +(end - start) +" 毫秒!"); } catch (SQLException e) { e.printStackTrace(); } } }
-- 元数据相关的命令介绍 -- 1.查看服务器当前状态 -- 2.查看MySQl的版本信息 -- 3.查询表中的详细信息 -- 4.显示数据表的详细索引信息 -- 5.列出所有数据库 -- 6.显示当前数据库的所有表 -- 7.获取当前的数据库名
通过JDBC 也可以获取到元数据,比如数据库的相关信息,或者当我们使用程序查询一个不熟悉的表时, 我们可以通过获取元素据信息,了解表中有多少个字段,字段的名称 和 字段的类型.
public class TestMetaData { //1.获取数据库相关的元数据信息 使用DatabaseMetaData @Test public void testDataBaseMetaData() throws SQLException { //1.获取数据库连接对象 connection Connection connection = DruidUtils.getConnection(); //2.获取代表数据库的 元数据对象 DatabaseMetaData DatabaseMetaData metaData = connection.getMetaData(); //3.获取数据库相关的元数据信息 String url = metaData.getURL(); System.out.println("数据库URL: " + url); String userName = metaData.getUserName(); System.out.println("当前用户: " + userName ); String productName = metaData.getDatabaseProductName(); System.out.println("数据库产品名: " + productName); String version = metaData.getDatabaseProductVersion(); System.out.println("数据库版本: " + version); String driverName = metaData.getDriverName(); System.out.println("驱动名称: " + driverName); //判断当前数据库是否只允许只读 boolean b = metaData.isReadOnly(); //如果是 true 就表示 只读 if(b){ System.out.println("当前数据库只允许读操作!"); }else{ System.out.println("不是只读数据库"); } connection.close(); } //获取结果集中的元数据信息 @Test public void testResultSetMetaData() throws SQLException { //1.获取连接 Connection con = DruidUtils.getConnection(); //2.获取预处理对象 PreparedStatement ps = con.prepareStatement("select * from employee"); ResultSet resultSet = ps.executeQuery(); //3.获取结果集元素据对象 ResultSetMetaData metaData = ps.getMetaData(); //1.获取当前结果集 共有多少列 int count = metaData.getColumnCount(); System.out.println("当前结果集中共有: " + count + " 列"); //2.获结果集中 列的名称 和 类型 for (int i = 1; i <= count; i++) { String columnName = metaData.getColumnName(i); System.out.println("列名: "+ columnName); String columnTypeName = metaData.getColumnTypeName(i); System.out.println("类型: " +columnTypeName); } //释放资源 DruidUtils.close(con,ps,resultSet); } }
以上是脚本宝典为你收集整理的数据库连接池&DBUtils全部内容,希望文章能够帮你解决数据库连接池&DBUtils所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。