前言:本文是对JDBC和数据库连接池的全面知识网络加项目实战 喜欢的小伙伴可以点赞评论 也欢迎大家评论区一起交流~
第19章 JDBC和数据库连接池
19.1 JDBC概述
JDBC好处
JDBC API
19.2 JDBC快速入门
import java.sql.*; import com.mysql.jdbc.Driver; import java.util.Properties; import java.util.logging.Logger; public class jdbc { public static void main(String[] args) throws SQLException { //前置工作: 在项目下创建一个文件夹比如 libs // 将 mysql.jar 拷贝到该目录下,点击 add to project ..加入到项目中 //1. 注册驱动 Driver driver = new Driver(); //2. 得到连接 //(1) jdbc:mysql:// 规定好表示协议,通过jdbc的方式连接mysql //(2) localhost 主机,可以是ip地址 //(3) 3306 表示mysql监听的端口 //(4) hsp_db02 连接到mysql dbms 的哪个数据库 //(5) mysql的连接本质就是前面学过的socket连接 //(6) useSSL=false 我们先采用false 配置较麻烦 String url="jdbc:mysql://localhost:3306/db1?useSSL=false"; //将 用户名和密码放入到Properties 对象 Properties properties=new Properties(); properties.setProperty("user","root"); properties.setProperty("password","123456"); Connection connect=driver.connect(url,properties); //3. 执行sql String sql="insert into temp_emp(empno,ename,sal) values(1009,'fy',12000)"; //statement 用于执行静态SQL语句并返回其生成的结果的对象 Statement statement=connect.createStatement(); int rows= statement.executeUpdate(sql); // 如果是 dml语句,返回的就是影响行数 System.out.println(rows>0?"success":"fail"); //4. 关闭连接资源 statement.close(); connect.close(); } }
19.3 获取数据库连接5种方式
方式1 静态加载 灵活性差 依赖强
public class JdbcConn {
//方式1
@Test
public void connect01() throws SQLException {
Driver driver = new Driver(); //创建driver对象
String url = "jdbc:mysql://localhost:3306/hsp_db02";
//将 用户名和密码放入到Properties 对象
Properties properties = new Properties();
//说明 user 和 password 是规定好,后面的值根据实际情况写
properties.setProperty("user", "root");// 用户
properties.setProperty("password", "hsp"); //密码
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
}
方式2 利用反射加载Driver类 动态加载 更灵活 降低依赖性
import java.sql.*; import com.mysql.jdbc.Driver; import java.util.Properties; import java.util.logging.Logger; public class jdbc { public static void main(String[] args) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { //1. 注册驱动 Class clazz=Class.forName("com.mysql.jdbc.Driver"); Driver driver= (Driver) clazz.newInstance(); //2. 得到连接 String url="jdbc:mysql://localhost:3306/db1?useSSL=false"; //将 用户名和密码放入到Properties 对象 Properties properties=new Properties(); properties.setProperty("user","root"); properties.setProperty("password","123456"); Connection connect=driver.connect(url,properties); //3. 执行sql String sql="insert into temp_emp(empno,ename,sal) values(1009,'fy',12000)"; //statement 用于执行静态SQL语句并返回其生成的结果的对象 Statement statement=connect.createStatement(); int rows= statement.executeUpdate(sql); // 如果是 dml语句,返回的就是影响行数 System.out.println(rows>0?"success":"fail"); //4. 关闭连接资源 statement.close(); connect.close(); } }
方式3 使用drivermaneger替代driver
import java.sql.*; import com.mysql.jdbc.Driver; import java.util.Properties; import java.util.logging.Logger; public class jdbc { public static void main(String[] args) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { //1. 注册驱动 Class clazz=Class.forName("com.mysql.jdbc.Driver"); Driver driver= (Driver) clazz.newInstance(); //2. 得到连接 String url="jdbc:mysql://localhost:3306/db1?useSSL=false"; String user="root"; String password="123456"; DriverManager.registerDriver(driver); Connection connection=DriverManager.getConnection(url,user,password); //3. 执行sql String sql="insert into temp_emp(empno,ename,sal) values(1009,'fy',12000)"; //statement 用于执行静态SQL语句并返回其生成的结果的对象 Statement statement=connection.createStatement(); int rows= statement.executeUpdate(sql); // 如果是 dml语句,返回的就是影响行数 System.out.println(rows>0?"success":"fail"); //4. 关闭连接资源 statement.close(); connection.close(); } }
方式4
import java.sql.*; import com.mysql.jdbc.Driver; import java.util.Properties; import java.util.logging.Logger; public class jdbc { public static void main(String[] args) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException { //1. 注册驱动 Class.forName("com.mysql.jdbc.Driver"); //2. 得到连接 String url="jdbc:mysql://localhost:3306/db1?useSSL=false"; String user="root"; String password="123456"; Connection connection=DriverManager.getConnection(url,user,password); //3. 执行sql String sql="insert into temp_emp(empno,ename,sal) values(1009,'fy',12000)"; //statement 用于执行静态SQL语句并返回其生成的结果的对象 Statement statement=connection.createStatement(); int rows= statement.executeUpdate(sql); // 如果是 dml语句,返回的就是影响行数 System.out.println(rows>0?"success":"fail"); //4. 关闭连接资源 statement.close(); connection.close(); } }
方式5
jdbc.java
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.*; import com.mysql.jdbc.Driver; import java.util.Properties; import java.util.logging.Logger; public class jdbc { public static void main(String[] args) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, IOException { Properties properties=new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); String url=properties.getProperty("url"); String user=properties.getProperty("user"); String password=properties.getProperty("password"); String driver=properties.getProperty("driver"); Class.forName(driver);//建议写上 更加明确 Connection connection=DriverManager.getConnection(url,user,password); String sql="insert into temp_emp(empno,ename,sal) values(1009,'fy',12000)"; Statement statement=connection.createStatement(); int rows= statement.executeUpdate(sql); // 如果是 dml语句,返回的就是影响行数 System.out.println(rows>0?"success":"fail"); statement.close(); connection.close(); } }
mysql.properties
user=root password=123456 driver=com.mysql.jdbc.Driver url = jdbc:mysql://localhost:3306/db1?rewriteBatchedStatements=true&useSSL=false # rewriteBatchedStatements用于优化批量SQL操作。 # 当设置为true时,JDBC驱动会尝试重写批量的INSERT、UPDATE、DELETE语句, # 以减少与数据库的交互次数,提高执行效率。 # 例如,多条INSERT语句可能会被重写成一条带有多个VALUES子句的INSERT语句。 # useSSL用于控制是否使用SSL连接到MySQL数据库。 # 当设置为true时,会尝试使用SSL建立安全连接;当设置为false时, # 则禁用SSL连接。如果没有显式设置此属性, # 根据MySQL 5.5.45+、5.6.26+和5.7.6+的要求,默认会尝试建立SSL连接。
注意:第五种通过使用Properties
文件来配置数据库连接信息是实际开发中最常用的一种方式 因为灵活性和可维护性比较强
19.4 resultset结果集
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.*; import com.mysql.jdbc.Driver; import java.util.Properties; import java.util.logging.Logger; public class jdbc { public static void main(String[] args) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, IOException { Properties properties=new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); String url=properties.getProperty("url"); String user=properties.getProperty("user"); String password=properties.getProperty("password"); String driver=properties.getProperty("driver"); Class.forName(driver);//建议写上 更加明确 Connection connection=DriverManager.getConnection(url,user,password); String sql="select empno,ename,sal,mgr,emp.deptno,loc from emp left join dept on emp.deptno=dept.deptno"; Statement statement=connection.createStatement(); ResultSet resultSet= statement.executeQuery(sql); // 如果是 dml语句,返回的就是影响行数 while(resultSet.next()){ int empno=resultSet.getInt(1); String ename= resultSet.getString(2); int sal=resultSet.getInt(3); int mgr=resultSet.getInt(4); int deptno=resultSet.getInt(5); String loc=resultSet.getString(6); System.out.printf("%-5d %-8s %-8d %-8d %-8d %-12s%n", empno, ename, sal, mgr, deptno, loc);//printf格式化对齐 } statement.close(); connection.close(); } }
19.5 statement
PreparedStatement 发送给MySQL的语句是编译过的,所以MySQL不用再编译,可以直接执行。
SQL注入
-- 演示sql 注入
-- 创建一张表
CREATE TABLE admin ( -- 管理员表
NAME VARCHAR(32) NOT NULL UNIQUE,
pwd VARCHAR(32) NOT NULL DEFAULT '') CHARACTER SET utf8;
-- 添加数据
INSERT INTO admin VALUES('tom', '123');
-- 查找某个管理是否存在
SELECT *
FROM admin
WHERE NAME = 'tom' AND pwd = '123'
-- SQL
-- 输入用户名 为 1' or
-- 输入万能密码 为 or '1'= '1
SELECT *
FROM admin
WHERE NAME = '1' OR' AND pwd = 'OR '1'= '1'
SELECT * FROM admin
什么是 SQL 注入?
SQL 注入是一种恶意攻击技术,攻击者通过在用户输入或其他数据源中插入恶意的 SQL 语句,来欺骗应用程序执行非预期的 SQL 命令。这可能导致数据泄露、数据损坏、权限提升甚至完全控制数据库服务器。
在你提供的示例中的 SQL 注入
在示例中:
- 首先创建了一个名为
admin
的表,包含NAME
和pwd
两个字段。 - 插入了一条数据
('tom', '123')
。 - 正常的查询语句是
SELECT * FROM admin WHERE NAME = 'tom' AND pwd = '123'
,这是用来验证用户名和密码是否匹配的。
然而,当用户输入恶意数据时:
- 用户名输入为
1' or
- 密码输入为
or '1' = '1
查询语句变成了SELECT * FROM admin WHERE NAME = '1' OR' AND pwd = 'OR '1' = '1'
。
- 这里的
'1' OR'
和'OR '1' = '1'
是攻击者注入的恶意代码。 - 由于 SQL 语句中的逻辑运算,
'1' = '1'
这个条件总是为真。所以这个查询语句会返回admin
表中的所有记录,攻击者就可以绕过正常的用户名和密码验证机制。
19.6 PreparedStatement
预处理好处
PreparedStatement 发送给MySQL的语句是编译过的,所以MySQL不用再编译,可以直接执行。
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.*; import com.mysql.jdbc.Driver; import java.util.Properties; import java.util.Scanner; import java.util.logging.Logger; public class jdbc { public static void main(String[] args) throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException, IOException { Properties properties=new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); String url=properties.getProperty("url"); String user=properties.getProperty("user"); String password=properties.getProperty("password"); String driver=properties.getProperty("driver"); Class.forName(driver);//建议写上 更加明确 Connection connection=DriverManager.getConnection(url,user,password); int deptno1,deptno2; System.out.println("请依次输入要查询的两个部门编号"); Scanner scanner=new Scanner(System.in); deptno1=scanner.nextInt(); deptno2=scanner.nextInt(); String sql = "select ename , empno,sal from emp where deptno=? or deptno=?"; PreparedStatement preparedStatement=connection.prepareStatement(sql); preparedStatement.setInt(1,deptno1); preparedStatement.setInt(2,deptno2); ResultSet resultSet= preparedStatement.executeQuery(); // 如果是 dml语句,返回的就是影响行数 while(resultSet.next()){ String ename=resultSet.getString(1); int empno=resultSet.getInt(2); int sal=resultSet.getInt(3); System.out.println(ename+"\t"+empno+"\t"+sal+"\t"); } resultSet.close();; preparedStatement.close(); connection.close(); } }
19.7 JDBC的相关API小结
19.8 封装JDBCUtils关闭连接 得到连接
JDBCUtils.java
import java.io.FileInputStream; import java.io.IOException; import java.sql.*; import java.util.Properties; /** * 这是一个工具类,完成 mysql的连接和关闭资源 */ public class JDBCUtils { //定义相关的属性(4个), 因为只需要一份,因此,我们做出static private static String user; //用户名 private static String password; //密码 private static String url; //url private static String driver; //驱动名 //在static代码块去初始化 static { try { Properties properties = new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); user = properties.getProperty("user"); password = properties.getProperty("password"); url = properties.getProperty("url"); driver = properties.getProperty("driver"); // 检查驱动加载 Class.forName(driver); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException(e); } } //连接数据库, 返回Connection public static Connection getConnection() { try { return DriverManager.getConnection(url, user, password); } catch (SQLException e) { //1. 将编译异常转成 运行异常 //2. 调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便. throw new RuntimeException(e); } } //关闭相关资源 /* 1. ResultSet 结果集 2. Statement 或者 PreparedStatement 3. Connection 4. 如果需要关闭资源,就传入对象,否则传入 null */ public static void close(ResultSet set, Statement statement, Connection connection) { //判断是否为null try { if (set != null) { set.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { //将编译异常转成运行异常抛出 throw new RuntimeException(e); } } }
JDBCUtils_Use.java
import org.junit.Test; import java.sql.*; /** * 该类演示如何使用JDBCUtils工具类,完成dml 和 select */ public class JDBCUtils_Use { @Test public void testSelect() { //1. 得到连接 Connection connection = null; //2. 组织一个sql String sql = "select * from emp where empno = ?"; PreparedStatement preparedStatement = null; ResultSet set = null; //3. 创建PreparedStatement 对象 try { connection = JDBCUtils.getConnection(); System.out.println(connection.getClass()); //com.mysql.jdbc.JDBC4Connection preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, 1002);//给?号赋值 //执行, 得到结果集 set = preparedStatement.executeQuery(); //遍历该结果集 while (set.next()) { int empno = set.getInt("empno"); String ename = set.getString("ename"); String job = set.getString("job"); Date hiredate = set.getDate("hiredate"); int deptno = set.getInt("deptno"); int sal=set.getInt("sal"); System.out.println(empno + "\t" + ename + "\t" + job + "\t" + hiredate + "\t" +sal+"\t"+ deptno); } } catch (SQLException e) { e.printStackTrace(); } finally { //关闭资源 JDBCUtils.close(set, preparedStatement, connection); } } @Test public void testDML() {//insert , update, delete //1. 得到连接 Connection connection = null; //2. 组织一个sql String sql = "update emp set sal = ? where empno = ?"; // 测试 delete 和 insert ,自己玩. PreparedStatement preparedStatement = null; //3. 创建PreparedStatement 对象 try { connection = JDBCUtils.getConnection(); preparedStatement = connection.prepareStatement(sql); //给占位符赋值 preparedStatement.setInt(1, 30000); preparedStatement.setInt(2, 1001); //执行 int rows = preparedStatement.executeUpdate(); System.out.println(rows > 0 ? "执行成功" : "执行失败"); } catch (SQLException e) { e.printStackTrace(); } finally { //关闭资源 JDBCUtils.close(null, preparedStatement, connection); } } }
封装 JDBCUtils 在实际开发很常用,意义如下:
- 代码复用:可复用连接获取及资源释放逻辑,避免多处重复编写相关代码。
- 可维护性提升:集中管理数据库连接配置,使业务与数据库底层操作分离,便于修改维护。
- 利于测试与扩展:方便单元测试时模拟或替换数据库相关功能,且易于扩展如添加连接池、事务管理等新功能。
19.9 事务
import org.junit.Test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * 演示jdbc 中如何使用事务 */ public class Transaction_ { //没有使用事务. @Test public void noTransaction() { //操作转账的业务 //1. 得到连接 Connection connection = null; //2. 组织一个sql String sql = "update account set balance = balance - 100 where id = 1"; String sql2 = "update account set balance = balance + 100 where id = 2"; PreparedStatement preparedStatement = null; //3. 创建PreparedStatement 对象 try { connection = JDBCUtils.getConnection(); // 在默认情况下,connection是默认自动提交 preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); // 执行第1条sql int i = 1 / 0; //抛出异常 preparedStatement = connection.prepareStatement(sql2); preparedStatement.executeUpdate(); // 执行第3条sql } catch (SQLException e) { e.printStackTrace(); } finally { //关闭资源 JDBCUtils.close(null, preparedStatement, connection); } } //事务来解决 @Test public void useTransaction() { //操作转账的业务 //1. 得到连接 Connection connection = null; //2. 组织一个sql String sql = "update account set balance = balance - 100 where id = 1"; String sql2 = "update account set balance = balance + 100 where id = 2"; PreparedStatement preparedStatement = null; //3. 创建PreparedStatement 对象 try { connection = JDBCUtils.getConnection(); // 在默认情况下,connection是默认自动提交 //将 connection 设置为不自动提交 connection.setAutoCommit(false); //开启了事务 preparedStatement = connection.prepareStatement(sql); preparedStatement.executeUpdate(); // 执行第1条sql int i = 1 / 0; //抛出异常 preparedStatement = connection.prepareStatement(sql2); preparedStatement.executeUpdate(); // 执行第2条sql //这里提交事务 connection.commit(); } catch (SQLException e) { //这里我们可以进行回滚,即撤销执行的SQL //默认回滚到事务开始的状态. System.out.println("执行发生了异常,撤销执行的sql"); try { connection.rollback(); } catch (SQLException throwables) { throwables.printStackTrace(); } e.printStackTrace(); } finally { //关闭资源 JDBCUtils.close(null, preparedStatement, connection); } } }
不用事务 异常后
用事务后 异常后
19.10 批处理
import org.junit.Test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; /** * 演示java的批处理 */ public class Batch_ { //传统方法,添加5000条数据到admin2 @Test public void noBatch() throws Exception { Connection connection = JDBCUtils.getConnection(); String sql = "insert into admin2 values(null, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); System.out.println("开始执行"); long start = System.currentTimeMillis();//开始时间 for (int i = 0; i < 5000; i++) {//5000执行 preparedStatement.setString(1, "jack" + i); preparedStatement.setString(2, "666"); preparedStatement.executeUpdate(); } long end = System.currentTimeMillis(); System.out.println("传统的方式 耗时=" + (end - start));//传统的方式 耗时=10702 //关闭连接 JDBCUtils.close(null, preparedStatement, connection); } //使用批量方式添加数据 @Test public void batch() throws Exception { Connection connection = JDBCUtils.getConnection(); String sql = "insert into admin2 values(null, ?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); System.out.println("开始执行"); long start = System.currentTimeMillis();//开始时间 for (int i = 0; i < 5000; i++) {//5000执行 preparedStatement.setString(1, "jack" + i); preparedStatement.setString(2, "666"); //将sql 语句加入到批处理包中 -> 看源码 /* //1. //第一就创建 ArrayList - elementData => Object[] //2. elementData => Object[] 就会存放我们预处理的sql语句 //3. 当elementData满后,就按照1.5扩容 //4. 当添加到指定的值后,就executeBatch //5. 批量处理会减少我们发送sql语句的网络开销,而且减少编译次数,因此效率提高 public void addBatch() throws SQLException { synchronized(this.checkClosed().getConnectionMutex()) { if (this.batchedArgs == null) { this.batchedArgs = new ArrayList(); } for(int i = 0; i < this.parameterValues.length; ++i) { this.checkAllParametersSet(this.parameterValues[i], this.parameterStreams[i], i); } this.batchedArgs.add(new PreparedStatement.BatchParams(this.parameterValues, this.parameterStreams, this.isStream, this.streamLengths, this.isNull)); } } */ preparedStatement.addBatch(); //当有1000条记录时,再批量执行 if((i + 1) % 1000 == 0) {//满1000条sql preparedStatement.executeBatch(); //清空一把 preparedStatement.clearBatch(); } } long end = System.currentTimeMillis(); System.out.println("批量方式 耗时=" + (end - start));//批量方式 耗时=108 //关闭连接 JDBCUtils.close(null, preparedStatement, connection); } }
不用batch
用batch
19.11 数据库连接池
数据库连接池种类
C3P0_.java
import com.mchange.v2.c3p0.ComboPooledDataSource; import org.junit.Test; import java.io.FileInputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * 演示c3p0的使用 */ public class C3P0_ { //方式1: 相关参数,在程序中指定user, url , password等 @Test public void testC3P0_01() throws Exception { //1. 创建一个数据源对象 ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource(); //2. 通过配置文件mysql.properties 获取相关连接的信息 Properties properties = new Properties(); properties.load(new FileInputStream("src\\mysql.properties")); //读取相关的属性值 String user = properties.getProperty("user"); String password = properties.getProperty("password"); String url = properties.getProperty("url"); String driver = properties.getProperty("driver"); //给数据源 comboPooledDataSource 设置相关的参数 //注意:连接管理是由 comboPooledDataSource 来管理 comboPooledDataSource.setDriverClass(driver); comboPooledDataSource.setJdbcUrl(url); comboPooledDataSource.setUser(user); comboPooledDataSource.setPassword(password); //设置初始化连接数 comboPooledDataSource.setInitialPoolSize(10); //最大连接数 comboPooledDataSource.setMaxPoolSize(50); //测试连接池的效率, 测试对mysql 5000次操作 long start = System.currentTimeMillis(); for (int i = 0; i < 5000; i++) { Connection connection = comboPooledDataSource.getConnection(); //这个方法就是从 DataSource 接口实现的 //System.out.println("连接OK"); connection.close(); //这里不是关闭,连接池重写了关闭方法,功能是回收连接!! } long end = System.currentTimeMillis(); //c3p0 5000连接mysql 耗时=391 System.out.println("c3p0 5000连接mysql 耗时=" + (end - start)); } //第二种方式 使用配置文件模板来完成 //1. 将c3p0 提供的 c3p0.config.xml 拷贝到 src目录下 //2. 该文件指定了连接数据库和连接池的相关参数 @Test public void testC3P0_02() throws SQLException { ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("fsl"); //测试5000次连接mysql long start = System.currentTimeMillis(); System.out.println("开始执行...."); for (int i = 0; i < 500000; i++) { Connection connection = comboPooledDataSource.getConnection(); //System.out.println("连接OK~"); connection.close(); } long end = System.currentTimeMillis(); //c3p0的第二种方式 耗时=413 System.out.println("c3p0的第二种方式(500000) 耗时=" + (end - start));//1917 } }
c3p0-config.xml
<c3p0-config> <!-- 数据源名称代表连接池 --> <named-config name="fsl"> <!-- 驱动类 --> <property name="driverClass">com.mysql.jdbc.Driver</property> <!-- url,这里添加了useSSL=false来禁用SSL连接 --> <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/db1?useSSL=false</property> <!-- 用户名 --> <property name="user">root</property> <!-- 密码 --> <property name="password">123456</property> <!-- 每次增长的连接数--> <property name="acquireIncrement">5</property> <!-- 初始的连接数 --> <property name="initialPoolSize">10</property> <!-- 最小连接数 --> <property name="minPoolSize">5</property> <!-- 最大连接数 --> <property name="maxPoolSize">50</property> <!-- 可连接的最多的命令对象数 --> <property name="maxStatements">5</property> <!-- 每个连接对象可连接的最多的命令对象数 --> <property name="maxStatementsPerConnection">2</property> </named-config> </c3p0-config>
实际开发中常用第二种配置文件 因为第一种比较笨重 不能通过配置文件进行修改
关于配置文件:
XML和Properties是比较常用的配置文件方式。
XML适用于复杂的企业级应用、框架配置和服务器配置,其层次化结构能清晰组织复杂信息,扩展性好,还可通过外部定义进行验证。
Properties用于简单配置,如数据库连接和基本属性设置,格式简单直观,在Java中读取处理很便捷。
除此之外,JSON和YAML也是常用的配置文件方式。JSON在前端开发等场景很常用,简洁且与JavaScript兼容;YAML在自动化部署和容器编排等领域应用广泛。
Druid
Druid_.java
import com.alibaba.druid.pool.DruidDataSourceFactory; import org.junit.Test; import javax.sql.DataSource; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.util.Properties; /** * 测试druid的使用 */ public class Druid_ { @Test public void testDruid() throws Exception { //1. 加入 Druid jar包 //2. 加入 配置文件 druid.properties , 将该文件拷贝项目的src目录 //3. 创建Properties对象, 读取配置文件 Properties properties = new Properties(); properties.load(new FileInputStream("src\\druid.properties")); //4. 创建一个指定参数的数据库连接池, Druid连接池 DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); long start = System.currentTimeMillis(); for (int i = 0; i < 500000; i++) { Connection connection = dataSource.getConnection(); System.out.println(connection.getClass()); //System.out.println("连接成功!"); connection.close(); } long end = System.currentTimeMillis(); //druid连接池 操作5000 耗时=412 System.out.println("druid连接池 操作500000 耗时=" + (end - start));//539 } }
druid.properties
#key=value driverClassName=com.mysql.jdbc.Driver username=root password=123456 url = jdbc:mysql://localhost:3306/db1?rewriteBatchedStatements=true&useSSL=false #initial connection Size initialSize=10 #min idle connecton size minIdle=5 #max active connection size maxActive=50 #max wait time(5000 mil seconds) maxWait=5000
注意:druid的配置文件中用户名是username,而c3p0要求是user,作者在这里卡了一会
将 JDBCUtils 工具类改成 Druid(德鲁伊)实现
JDBCUtilsByDruid.java
import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.FileInputStream; 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 JDBCUtilsByDruid { private static DataSource ds; //在静态代码块完成 ds初始化 static { Properties properties = new Properties(); try { properties.load(new FileInputStream("src\\druid.properties")); ds = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { e.printStackTrace(); } } //编写getConnection方法 public static Connection getConnection() throws SQLException { return ds.getConnection(); } //关闭连接, 老师再次强调: 在数据库连接池技术中,close 不是真的断掉连接 //而是把使用的Connection对象放回连接池 public static void close(ResultSet resultSet, Statement statement, Connection connection) { try { if (resultSet != null) { resultSet.close(); } if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { throw new RuntimeException(e); } } }
JDBCUtilsByDruid_USE.java
import org.junit.Test; import java.sql.*; import java.util.ArrayList; @SuppressWarnings({"all"}) public class JDBCUtilsByDruid_USE { @Test public void testSelect() { System.out.println("使用 druid方式完成"); //1. 得到连接 Connection connection = null; //2. 组织一个sql String sql = "select * from emp where empno >= ?"; PreparedStatement preparedStatement = null; ResultSet set = null; //3. 创建PreparedStatement 对象 try { connection = JDBCUtilsByDruid.getConnection(); System.out.println(connection.getClass());//运行类型 com.alibaba.druid.pool.DruidPooledConnection preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1, 1005);//给?号赋值 //执行, 得到结果集 set = preparedStatement.executeQuery(); //遍历该结果集 while (set.next()) { int id = set.getInt("empno"); String name = set.getString("ename");//getName() String job = set.getString("job");//getSex() Date hiredate = set.getDate("hiredate"); System.out.println(id + "\t" + name + "\t" + job + "\t" + hiredate + "\t"); } } catch (SQLException e) { e.printStackTrace(); } finally { //关闭资源 JDBCUtilsByDruid.close(set, preparedStatement, connection); } } }
个人理解:
将 JDBCUtils 工具类改为 Druid 实现主要带来的最重要优势就是在高并发场景下性能更好。
19.12 Apache-DBUtils
import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.junit.Test; import java.sql.*; import java.util.ArrayList; import java.util.List; @SuppressWarnings({"all"}) public class DBUtils { //使用apache-DBUtils 工具类 + druid 完成对表的crud操作 @Test public void testQueryMany() throws SQLException { //返回结果是多行的情况 //1. 得到 连接 (druid) Connection connection = JDBCUtilsByDruid.getConnection(); //2. 使用 DBUtils 类和接口 , 先引入DBUtils 相关的jar , 加入到本Project //3. 创建 QueryRunner QueryRunner queryRunner = new QueryRunner(); //4. 就可以执行相关的方法,返回ArrayList 结果集 //String sql = "select * from actor where id >= ?"; // 注意: sql 语句也可以查询部分列 String sql = "select empno, ename from emp where empno >= ?"; // 老韩解读 //(1) query 方法就是执行sql 语句,得到resultset ---封装到 --> ArrayList 集合中 //(2) 返回集合 //(3) connection: 连接 //(4) sql : 执行的sql语句 //(5) new BeanListHandler<>(Actor.class): 将resultset -> Actor 对象 -> 封装到 ArrayList // 底层使用反射机制 去获取Actor 类的属性,然后进行封装 //(6) 1 就是给 sql 语句中的? 赋值,可以有多个值,因为是可变参数 Object... params //(7) 底层得到的resultset ,会在query 关闭, 同时也会关闭PreparedStatment /** * 分析 queryRunner.query方法: * public <T> T query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException { * PreparedStatement stmt = null;//定义PreparedStatement * ResultSet rs = null;//接收返回的 ResultSet * Object result = null;//返回ArrayList * try { * stmt = this.prepareStatement(conn, sql);//创建PreparedStatement * this.fillStatement(stmt, params);//对sql 进行 ? 赋值 * rs = this.wrap(stmt.executeQuery());//执行sql,返回resultset * result = rsh.handle(rs);//返回的resultset --> arrayList[result] [使用到反射,对传入class对象处理] * } catch (SQLException var33) { * this.rethrow(var33, sql, params); * } finally { * try { * this.close(rs);//关闭resultset * } finally { * this.close((Statement)stmt);//关闭preparedstatement对象 * } * } * return result; * } */ List<Emp> list = queryRunner.query(connection, sql, new BeanListHandler<>(Emp.class), 1005); System.out.println("输出集合的信息"); for (Emp emp : list) { System.out.print(emp); } //释放资源 JDBCUtilsByDruid.close(null, null, connection); } //演示 apache-dbutils + druid 完成 返回的结果是单行记录(单个对象) @Test public void testQuerySingle() throws SQLException { //1. 得到 连接 (druid) Connection connection = JDBCUtilsByDruid.getConnection(); //2. 使用 DBUtils 类和接口 , 先引入DBUtils 相关的jar , 加入到本Project //3. 创建 QueryRunner QueryRunner queryRunner = new QueryRunner(); //4. 就可以执行相关的方法,返回单个对象 String sql = "select * from emp where empno = ?"; // 老韩解读 // 因为我们返回的单行记录<--->单个对象 , 使用的Hander 是 BeanHandler Emp emp= queryRunner.query(connection, sql, new BeanHandler<>(Emp.class), 1001); System.out.println(emp); // 释放资源 JDBCUtilsByDruid.close(null, null, connection); } //演示apache-dbutils + druid 完成查询结果是单行单列-返回的就是object @Test public void testScalar() throws SQLException { //scalar 在java中往往表示单行单列的那个值 //1. 得到 连接 (druid) Connection connection = JDBCUtilsByDruid.getConnection(); //2. 使用 DBUtils 类和接口 , 先引入DBUtils 相关的jar , 加入到本Project //3. 创建 QueryRunner QueryRunner queryRunner = new QueryRunner(); //4. 就可以执行相关的方法,返回单行单列 , 返回的就是Object String sql = "select ename from emp where empno = ?"; //老师解读: 因为返回的是一个对象, 使用的handler 就是 ScalarHandler Object obj = queryRunner.query(connection, sql, new ScalarHandler(), 1001); System.out.println(obj); // 释放资源 JDBCUtilsByDruid.close(null, null, connection); } //演示apache-dbutils + druid 完成 dml (update, insert ,delete) @Test public void testDML() throws SQLException { //1. 得到 连接 (druid) Connection connection = JDBCUtilsByDruid.getConnection(); //2. 使用 DBUtils 类和接口 , 先引入DBUtils 相关的jar , 加入到本Project //3. 创建 QueryRunner QueryRunner queryRunner = new QueryRunner(); //4. 这里组织sql 完成 update, insert delete //String sql = "update actor set name = ? where id = ?"; //String sql = "insert into actor values(null, ?, ?, ?, ?)"; String sql = "delete from emp where empno = ?"; //老韩解读 //(1) 执行dml 操作是 queryRunner.update() //(2) 返回的值是受影响的行数 (affected: 受影响) //int affectedRow = queryRunner.update(connection, sql, "林青霞", "女", "1966-10-10", "116"); int affectedRow = queryRunner.update(connection, sql, 1009 ); System.out.println(affectedRow > 0 ? "执行成功" : "执行没有影响到表"); // 释放资源 JDBCUtilsByDruid.close(null, null, connection); } }
表和 JavaBean 的类型映射关系
19.13 DAO 和增删改查通用方法-BasicDao
总体架构
- 分层设计:
- 图中展示了一个典型的三层架构,包括界面层(AppView)、业务逻辑层(包括 ActorService、GoodsService 和 OrderService)和数据访问层(包括 ActorDAO、GoodsDAO 和 OrderDAO)。
- 每一层都有其特定的功能,并且通过接口进行交互,这种设计有助于提高代码的可维护性和可扩展性。
界面层(AppView)
- 位置和功能:
- 位于图的右上角,用蓝色椭圆表示。
- 这一层是用户与系统交互的接口,负责调用业务逻辑层的服务来获取数据并展示给用户。例如,当用户在界面上执行一个操作(如查询订单)时,AppView 会调用 OrderService 来处理请求。
业务逻辑层
- ActorService、GoodsService 和 OrderService:
- 分别位于图的中上部,用蓝色矩形表示。
- 这些服务类负责处理具体的业务逻辑。例如:
- ActorService 负责处理与演员(Actor)相关的业务逻辑,包括组织 SQL 语句并调用 ActorDAO 来完成对 actor 表的增删改查操作。
- GoodsService 负责处理与商品(Goods)相关的业务逻辑,调用 GoodsDAO 来操作 goods 表。
- OrderService 负责处理与订单(Order)相关的业务逻辑,调用 OrderDAO 来操作 order 表。
数据访问层
- ActorDAO、GoodsDAO 和 OrderDAO:
- 分别位于图的中部,用蓝色矩形表示。
- 这些数据访问对象(DAO)负责与数据库进行交互,执行具体的增删改查操作。例如:
- ActorDAO 负责对 actor 表进行操作,包括增、删、改、查。
- GoodsDAO 负责对 goods 表进行操作。
- OrderDAO 负责对 order 表进行操作。
基础操作(BasicOperation)
- 位置和功能:
- 位于图的左侧,用蓝色矩形表示。
- 这一部分可能包含一些通用的、基础的数据库操作方法,供各个 DAO 使用,以简化代码并提高代码的可维护性和可读性。
测试数据访问对象(TestDAO)
- 位置和功能:
- 位于图的左上方,用蓝色矩形表示。
- 用于测试数据访问层的功能,根据业务需求使用对应的 DAO 进行测试,确保数据操作的正确性。
数据库(MySQL)
- 位置和功能:
- 位于图的下方,用蓝色矩形表示。
- 这是系统的数据存储层,包含多个数据表(actor 表、goods 表和 order 表),用于存储系统的数据。
实体类(Actor 类、Goods 类和 Order 类)
- 位置和功能:
- 分别位于图的左下角,用蓝色矩形表示。
- 这些实体类(POJO - Plain Old Java Object)对应数据库中的表结构,用于在程序中表示和操作数据。例如,Actor 类对应 actor 表,包含表中的各个字段属性。
工具类(jdbcUtilByDruid 工具类)
- 位置和功能:
- 位于图的右下角,用蓝色矩形表示。
- 这是一个用于数据库连接的工具类,可能使用了 Druid 连接池来管理数据库连接,提供了获取和释放连接的方法,确保数据库操作的高效和稳定。
箭头和关系
- 表示的数据流向:
- 图中的箭头表示数据和操作的流向。例如,从 AppView 指向 ActorService 的箭头表示 AppView 会调用 ActorService 的方法;从 ActorService 指向 ActorDAO 的箭头表示 ActorService 会调用 ActorDAO 来操作数据库。
怎么理解DAO?
在软件开发中,DAO(Data Access Object,数据访问对象)是一种设计模式,用于将数据访问逻辑与业务逻辑分离。
TestDAO.java
import org.junit.Test; import java.util.List; public class TestDAO { //测试ActorDAO 对actor表crud操作 @Test public void testActorDAO() { EmpDAO emprDAO = new EmpDAO(); List<Emp> emps = emprDAO.queryMulti("select * from emp where empno >=?", Emp.class, 1005); System.out.println("===查询结果==="); for (Emp emp : emps) { System.out.println(emp); } //2. 查询单行记录 Emp emp = emprDAO.querySingle("select * from emp where empno = ?", Emp.class, 1007); System.out.println("====查询单行结果===="); System.out.println(emp); //3. 查询单行单列 Object o = emprDAO.queryScalar("select ename from emp where empno = ?", 1006); System.out.println("====查询单行单列值==="); System.out.println(o); //4. dml操作 insert ,update, delete int update = emprDAO.update("insert into emp values(?, ?, ?, ?, ?,?,?)", 1014,"张无忌", "market",1014, "2000-11-11", "9999","7"); System.out.println(update > 0 ? "执行成功" : "执行没有影响表"); } }
BasicDAO.java
import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import java.sql.Connection; import java.sql.SQLException; import java.util.List; /** * 开发BasicDAO , 是其他DAO的父类 */ public class BasicDAO<T> { //泛型指定具体类型 private QueryRunner qr = new QueryRunner(); //开发通用的dml方法, 针对任意的表 public int update(String sql, Object... parameters) { Connection connection = null; try { connection = JDBCUtilsByDruid.getConnection(); int update = qr.update(connection, sql, parameters); return update; } catch (SQLException e) { throw new RuntimeException(e); //将编译异常->运行异常 ,抛出 } finally { JDBCUtilsByDruid.close(null, null, connection); } } //返回多个对象(即查询的结果是多行), 针对任意表 /** * @param sql sql 语句,可以有 ? * @param clazz 传入一个类的Class对象 比如 Actor.class * @param parameters 传入 ? 的具体的值,可以是多个 * @return 根据Actor.class 返回对应的 ArrayList 集合 */ public List<T> queryMulti(String sql, Class<T> clazz, Object... parameters) { Connection connection = null; try { connection = JDBCUtilsByDruid.getConnection(); return qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters); } catch (SQLException e) { throw new RuntimeException(e); //将编译异常->运行异常 ,抛出 } finally { JDBCUtilsByDruid.close(null, null, connection); } } //查询单行结果 的通用方法 public T querySingle(String sql, Class<T> clazz, Object... parameters) { Connection connection = null; try { connection = JDBCUtilsByDruid.getConnection(); return qr.query(connection, sql, new BeanHandler<T>(clazz), parameters); } catch (SQLException e) { throw new RuntimeException(e); //将编译异常->运行异常 ,抛出 } finally { JDBCUtilsByDruid.close(null, null, connection); } } //查询单行单列的方法,即返回单值的方法 public Object queryScalar(String sql, Object... parameters) { Connection connection = null; try { connection = JDBCUtilsByDruid.getConnection(); return qr.query(connection, sql, new ScalarHandler(), parameters); } catch (SQLException e) { throw new RuntimeException(e); //将编译异常->运行异常 ,抛出 } finally { JDBCUtilsByDruid.close(null, null, connection); } } }
BasicDAO.java
import java.util.List; public class EmpDAO extends BasicDAO<Emp> { //1. 就有 BasicDAO 的方法 //2. 根据业务需求,可以编写特有的方法. }
个人理解:
- Druid是高性能连接池,避免频繁创建和销毁连接的性能开销,在高并发场景优势明显,还提供丰富的监控功能和灵活的配置,便于查看连接池状态和调整参数。
- DBUtils减少了JDBC的大量重复代码,将复杂操作步骤封装,通过简单方法调用就能完成操作。其结果集处理器很方便,能利用反射自动填充对象,提升开发效率。
- DAO设计模式将数据访问和业务逻辑分离,业务逻辑层只需调用DAO层方法完成数据操作,不用关心细节。它还能让代码复用,当数据库相关内容变化时,只需修改DAO层实现,提升了代码的维护性和扩展性。
- 三者结合从连接管理、操作简化和架构设计等方面简化JDBC编程,提升开发效率、系统性能和可维护性。