笔记目录:(https://www.cnblogs.com/wenjie2000/p/16378441.html)
基本介绍
JDBC为访问不同的数据库提供了统一的接口,为使用者屏蔽了细节问题。
Java程序员使用JDBC,可以连接任何提供了JDBC驱动程序的数据库系统,从而完成对数据库的各种操作。
JDBC的基本原理图
模拟JDBC
/*java规定的jdbc接口*/
public interface JdbcInterface {
//连接
public Object getConnection() ;
//crud
public void crud();
//关闭连接
public void close();
}
//mysql 数据库实现了 jdbc 接口 [模拟] 【mysql 厂商开发】
public class MysqlJdbcImpl implements JdbcInterface{
@Override
public Object getConnection() {
System.out.println("得到 mysql 的连接");
return null;
}
@Override
public void crud() {
System.out.println("完成 mysql 增删改查");
}
@Override
public void close() {
System.out.println("关闭 mysql 的连接");
}
}
//模拟 oracle 数据库实现 jdbc
public class OracleJdbcImpl implements JdbcInterface {
@Override
public Object getConnection() {
System.out.println("得到 oracle 的连接 升级");
return null;
}
@Override
public void crud() {
System.out.println("完成 对 oracle 的增删改查");
}
@Override
public void close() {
System.out.println("关闭 oracle 的连接");
}
}
//我们的操作--通过接口调用实现功能
public class TestJDBC {
public static void main(String[] args) throws Exception {
//完成对 mysql 的操作
JdbcInterface jdbcInterface = new MysqlJdbcImpl();
jdbcInterface.getConnection(); //通过接口来调用实现类[动态绑定]
jdbcInterface.crud();
jdbcInterface.close();
//完成对 oracle 的操作
System.out.println("==============================");
jdbcInterface = new OracleJdbcImpl();
jdbcInterface.getConnection(); //通过接口来调用实现类[动态绑定]
jdbcInterface.crud();
jdbcInterface.close();
}
}
JDBC 带来的好处
如果Java直接访问数据库(示意图)
JDBC带来的好处(示意图)
说明:JDBC是Java提供一套用于数据库操作的接口API,Java程序员只需要面向这套接口编程即可。不同的数据库厂商,需要针对这套接口,提供不同实现。
JDBC API
JDBC API是一系列的接口,它统一和规范了应用程序与数据库的连接、执行SQL语句,并到得到返回结果等各类操作,相关类和接口在java.sql与javax.sql包中
JDBC程序编写步骤
JDBC第一个程序
诵讨jdbc对表actor讲行添加,删除和修改操作
use db02;
create table actor (-- 演员表
id int primary key auto_increment,
name varchar(32) not null default '',
sex char(1) not null default '女',
borndate datetime,
phone varchar(12));
JDBC 第一个程序
先引入mysql的驱动文件()注意:驱动程序与mysql的版本号不同是正常状况,驱动文件版本号命名不是以mysql版本为准。
以下为驱动版本兼容的的mysql和java的版本信息。
把下载好的驱动文件复制到代码文件夹中
将其加入到项目中(对该文件右键,选择Add as Library...)
如果看到jar文件中的结构那么就添加成功
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class Jdbc01 {
public static void main(String[] args) throws SQLException {
//前置工作: 在项目下创建一个文件夹比如 libs
// 将 mysql.jar 拷贝到该目录下,点击 add to project ..加入到项目中
//1. 注册驱动
Driver driver = new Driver(); //创建 driver 对象
//2. 得到连接
// 老师解读
//(1) jdbc:mysql:// 规定好表示协议,通过 jdbc 的方式连接 mysql
//(2) localhost 主机,可以是 ip 地址
//(3) 3306 表示 mysql 监听的端口
//(4) hsp_db02 连接到 mysql dbms 的哪个数据库
//(5) mysql 的连接本质就是前面学过的 socket 连接
String url = "jdbc:mysql://localhost:3306/db02";
//将 用户名和密码放入到 Properties 对象
Properties properties = new Properties();
//说明 user 和 password 是规定好,后面的值根据实际情况写
properties.setProperty("user", "root");// 用户
properties.setProperty("password", "123456"); //密码
Connection connect = driver.connect(url, properties);
//3. 执行 sql
String sql = "insert into actor values(null, '刘德华', '男', '1970-11-11', '110')";
//String sql = "update actor set name='周星驰' where id = 1";
//String sql = "delete from actor where id = 1";
//statement 用于执行静态 SQL 语句并返回其生成的结果的对象
Statement statement = connect.createStatement();
int rows = statement.executeUpdate(sql); // 如果是 dml 语句,返回的就是影响行数System.out.println(rows > 0 ? "成功" : "失败");
//4. 关闭连接资源
statement.close();
connect.close();
}
}
获取数据库连接 5 种方式
方式1
//获取Driver实现类对象
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/db02";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "hsp");
Connection conn = driver.connect(url, info);
System.out.println(conn);
方式2
//方式1会直接使用com.mysql.jdbc.Driver(),属于静态加载,灵活性差,依赖强
//---推出--->方式2
Class clazz =Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url = "jdbc:mysql://localhost:3306/db02";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "abc123");
Connection conn = driver.connect(url,info);
System.out.printIn(conn);
方式3
//不创建Properties,使用DriverManager替换Driver
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url = "jdbc:mysql://localhost:3306/jdbc_db";
String user = "root";
String password = "hsp";
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println(conn);
方式4(推荐使用,不太灵活)
//使用Class.forName自动完成注册驱动,简化代码=>分析源码
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/db02";
String user ="root";
String password = "123456";
Connection conn = DriverManager.getConnection(url,user,password);
System.out.println(conn);
提示:
方式5(最推荐使用)
在方式 4 的基础上改进,增加配置文件,让连接 mysql 更加灵活
端口,数据库,用户名,密码为了方便,我们可以将信息写入到.properties文件中,方便操作
jdbc.properties文件内容:
user=root
password=1
url=jdbc:mysql://localhost:3306/db02
driver=com.mysql.jdbc.Driver
//通过 Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);//建议写上
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("方式 5 " + connection);
课堂练习
以下全使用java实现(实现很简单,我就不写了)
基本介绍
表示数据库结果集的数据表,通常通过执行查询数据库的语句生成
ResultSet对象保持一个光标指向其当前的数据行。最初,光标位于第一行之前
next方法将光标移动到下一行,并且由于在ResultSet对象中没有更多行时返回false ,因此可以在while循环中使用循环来遍历结果集
应用实例
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
//演示 select 语句返回 ResultSet ,并取出结果
public class ResultSet_ {
public static void main(String[] args) throws Exception {
//通过 Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
//1. 注册驱动
Class.forName(driver);//建议写上
//2. 得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3. 得到 Statement
Statement statement = connection.createStatement();
//4. 组织 SqL
String sql = "select id, name , sex, borndate from actor";
//执行给定的 SQL 语句,该语句返回单个 ResultSet 对象
/*
+----+-----------+-----+---------------------+
| id | name | sex | borndate |
+----+-----------+-----+---------------------+-------+
| 4 | 刘德华 | 男 | 1970-12-12 00:00:00 |
| 5 | jack | 男 | 1990-11-11 00:00:00 |
+----+-----------+-----+---------------------+-------+
*/
/*
阅读 debug 代码 resultSet 对象的结构
*/
ResultSet resultSet = statement.executeQuery(sql);
//5. 使用 while 取出数据
while (resultSet.next()) { // 让光标向后移动,如果没有更多行,则返回 false
int id = resultSet.getInt(1); //获取该行的第 1 列
//int id1 = resultSet.getInt("id"); 通过列名来获取值, 推荐
String name = resultSet.getString(2);//获取该行的第 2 列
String sex = resultSet.getString(3);
Date date = resultSet.getDate(4);
System.out.println(id + "\t" + name + "\t" + sex + "\t" + date);
}
//6. 关闭连接
resultSet.close();
statement.close();
connection.close();
}
}
基本介绍
Statement对象用于执行静态SQL语句并返回其生成的结果的对象
在连接建立后,需要对数据库进行访问,执行命名或是SQL语句,可以通过
Statement [存在SQL注入,实际开发一定不要用]
PreparedStatement [预处理]
CallableStatement [存储过程]
Statement对象执行SQL语句,存在SQL注入风险
SQL注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句段或命令,恶意攻击数据库。以下为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'),('tom2', '1234');
-- 查找某个管理是否存在
-- 正常语句
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'
-- 这个必定会查到数据,因而导致系统误判,认为账号和密码正确
要防范SQL注入,只要用 PreparedStatement(从Statement扩展而来)取代 Statement就可以了
基本介绍
预处理好处
应用案例
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;
//演示 PreparedStatement 使用 select 语句
public class PreparedStatement_ {
public static void main(String[] args) throws Exception {
//看 PreparedStatement 类图
Scanner scanner = new Scanner(System.in);
//让用户输入管理员名和密码
System.out.print("请输入管理员的名字: "); //next(): 当接收到 空格或者 '就是表示结束
String admin_name = scanner.nextLine(); // 说明,如果希望看到 SQL 注入,这里需要用nextLine
System.out.print("请输入管理员的密码: ");
String admin_pwd = scanner.nextLine();
//通过 Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
//1. 注册驱动
Class.forName(driver);//建议写上
//2. 得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3. 得到 PreparedStatement
//3.1 组织 SqL , Sql 语句的 ? 就相当于占位符
String sql = "select name , pwd from admin where name =? and pwd = ?";
//3.2 preparedStatement 对象实现了 PreparedStatement 接口的实现类的对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//3.3 给 ? 赋值
preparedStatement.setString(1, admin_name);
preparedStatement.setString(2, admin_pwd);
//4. 执行 select 语句使用 executeQuery
// 如果执行的是 dml(update, insert ,delete) executeUpdate()
// 这里执行 executeQuery ,不要再写 sql
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) { //如果查询到一条记录,则说明该管理存在
System.out.println("恭喜, 登录成功");
} else {
System.out.println("对不起,登录失败");
}
//关闭连接
resultSet.close();
preparedStatement.close();
connection.close();
}
}
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.Scanner;
//演示 PreparedStatement 使用 delete/insert/update 语句
public class PreparedStatementDML_ {
public static void main(String[] args) throws Exception {
//看 PreparedStatement 类图
Scanner scanner = new Scanner(System.in);
//让用户输入管理员名和密码
System.out.print("请输删除管理员的名字: "); //next(): 当接收到 空格或者 '就是表示结束
String admin_name = scanner.nextLine(); // 说明,如果希望看到 SQL 注入,这里需要用nextLine
// System.out.print("请输入管理员的新密码: ");
// String admin_pwd = scanner.nextLine();
//通过 Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
//1. 注册驱动
Class.forName(driver);//建议写上
//2. 得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3. 得到 PreparedStatement
//3.1 组织 SqL , Sql 语句的 ? 就相当于占位符
//添加记录
//String sql = "insert into admin values(?, ?)";
//String sql = "update admin set pwd = ? where name = ?";
String sql = "delete from admin where name = ?";
//3.2 preparedStatement 对象实现了 PreparedStatement 接口的实现类的对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//3.3 给 ? 赋值
preparedStatement.setString(1, admin_name);
//preparedStatement.setString(2, admin_name);
//4. 执行 dml 语句使用 executeUpdate
int rows = preparedStatement.executeUpdate();
System.out.println(rows > 0 ? "执行成功" : "执行失败");
//关闭连接
preparedStatement.close();
connection.close();
}
}
课堂练习
参考上面代码,代码没难度,我就不写了
说明
在jdbc操作中,获取连接和释放资源是经常使用到,可以将其封装JDBC连接的工具类JDBCUtils
实际使用使用工具类 JDBCUtils
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\\jdbc.properties"));
//读取相关的属性值
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
driver = properties.getProperty("driver");
} catch (IOException e) {
//在实际开发中,我们可以这样处理
//1. 将编译异常转成 运行异常
//2. 调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便.
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);
}
}
}
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 actor where id = ?";
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, 5);//给?号赋值
//执行, 得到结果集
set = preparedStatement.executeQuery();
//遍历该结果集
while (set.next()) {
int id = set.getInt("id");
String name = set.getString("name");
String sex = set.getString("sex");
Date borndate = set.getDate("borndate");
String phone = set.getString("phone");
System.out.println(id + "\t" + name + "\t" + sex + "\t" + borndate + "\t" + phone);
}
} 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 actor set name = ? where id = ?";
// 测试 delete 和 insert ,自己玩.
PreparedStatement preparedStatement = null;
//3. 创建 PreparedStatement 对象
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
//给占位符赋值
preparedStatement.setString(1, "周星驰");
preparedStatement.setInt(2, 4);
//执行
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.close(null, preparedStatement, connection);//注意,因为PreparedStatement继承了Statement,所以可以用来关闭preparedStatement
}
}
}
基本介绍
应用实例
模拟经典的转账业务
先创建表:
create table account(
id int primary key auto_increment,
name varchar(32) not null default '',
balance double not null default 0) character set utf8;
insert into account values(null,'马云',3000);
insert into account values(null,'马化腾',10000);
//没有使用事务.
@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(); // 执行第 3 条 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);
}
}
基本介绍
当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。
JDBC的批量处理语句包括下面方法:
addBatch():添加需要批量处理的SQL语句或参数
executeBatch(): 执行批量处理语句;
clearBatch():清空批处理包的语句
JDBC连接MySQL时,如果要使用批处理功能,必须在url中原先的末尾添加参数:
?rewriteBatchedStatements=true(如果不添加,底层就还是使用之前的方式添加)
批处理往往和PreparedStatement一起搭配使用,可以既减少编译次数,又减少运行次数,效率大大提高
应用实例
create table admin2(
id int primary key auto_increment,
username varchar(32) not null,
password varchar(32) not null);
//使用批量方式添加数据
@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);
}
传统获取Connection问题分析
数据库连接池种类
JDBC的数据库连接池使用javax.sql.DataSource来表示,DataSource只是一个接口,该接口通常由第三方提供实现[提供.jar]
C3P0数据库连接池,速度相对较慢(只是相较于其他连接池而言,但本身依然很快),稳定性不错(hibernate, spring)
DBCP数据库连接池,速度相对c3p0较快,但不稳定
Proxool数据库连接池,有监控连接池状态的功能,稳定性较c3p0差一点
BoneCP数据库连接池,速度快
Druid(德鲁伊)是阿里提供的数据库连接池,集DBCP、C3PO、Proxool优点于一身的数据库连接池
实际开发推荐使用Druid,但是由于C3P0出来时间早,也有许多公司在用。其它连接池不推荐使用。
c3p0 数据库连接池,驱动文件放src目录下(使用方法和之前的mysql驱动包一样)(下载)
使用方式一:
//方式 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\\jdbc.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 500000 次操作
long start = System.currentTimeMillis();
for (int i = 0; i < 500000; i++) {
Connection connection = comboPooledDataSource.getConnection(); //这个方法就是从DataSource接口实现的
//System.out.println("连接 OK");
connection.close();
}
long end = System.currentTimeMillis();
//c3p0 500000 连接 mysql 耗时=2291
System.out.println("c3p0 500000 连接 mysql 耗时=" + (end - start));//2291s
}
使用方式二:
c3p0配置文件"c3p0-config.xml"放到src自录下
<!-- c3p0-config.xml -->
<c3p0-config>
<!-- 数据源名称代表连接池 -->
<named-config name="hsp_edu">
<!-- 驱动类 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<!-- url-->
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/db02</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>
//第二种方式 使用配置文件模板来完成
//1. 将 c3p0 提供的 c3p0.config.xml 拷贝到 src 目录下
//2. 该文件指定了连接数据库和连接池的相关参数,注意需要根据自己的实际情况进行更改该文件
@Test
public void testC3P0_02() throws SQLException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("hsp_edu");//"hsp_edu"为配置文件中named-config处的name,可自己设置
//测试 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 的第二种方式 耗时=2138
System.out.println("c3p0 的第二种方式(500000) 耗时=" + (end - start));//2138s
}
druid数据库连接池,驱动文件放src目录下(使用方法和之前的mysql驱动包一样)(下载)
druid配置文件"druid.properties"放src自录下
# druid.properties
#key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db02?rewriteBatchedStatements=true
username=root
password=123456
#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 的使用
@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 连接池 操作 500000 耗时=807
System.out.println("druid 连接池 操作 500000 耗时=" + (end - start));//807s
}
将 JDBCUtils 工具类改成 Druid(德鲁伊)实现
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
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);
}
}
}
先分析一个问题
关闭connection后,resultSet结果集无法使用
resultSet不利于数据的管理
示意图
DBUtils基本介绍
DbUtils类
ArrayHandler:把结果集中的第一行数据转成对象数组。
ArrayListHandler:把结果集中的每一行数据都转成一个数组,再存放到List中。
BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。
BeanListHandler: 将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。
ColumnListHandler:将结果集中某一列的数据存放到List中。
KeyedHandler(name):将结果集中的每行数据都封装到Map里,再把这些map再存到一个map里,其key为指定的key.
MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List
应用实例
使用DBUtils+数据连接池(德鲁伊)方式,完成对表actor的增删改查
先将”commons-dbutils-1.3.jar“放到项目中,和之前的mysql驱动方法一样
先创建数据库中表对应的类
import java.util.Date;
/**
* Actor 对象和 actor 表的记录对应
*/
public class Actor { //Javabean, POJO, Domain 对象
private Integer id;
private String name;
private String sex;
private Date borndate;
private String phone;
public Actor() { //一定要给一个无参构造器[反射需要]
}
public Actor(Integer id, String name, String sex, Date borndate, String phone) {
this.id = id;
this.name = name;
this.sex = sex;
this.borndate = borndate;
this.phone = phone;
}
public Integer getId() {return id;}
public void setId(Integer id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getSex() {return sex;}
public void setSex(String sex) {this.sex = sex;}
public Date getBorndate() {return borndate;}
public void setBorndate(Date borndate) {this.borndate = borndate;}
public String getPhone() {return phone;}
public void setPhone(String phone) {this.phone = phone;}
@Override
public String toString() {
return "\nActor{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", borndate=" + borndate +
", phone='" + phone + '\'' +
'}';
}
}
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_USE {
//使用 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 id, name from actor where id >= ?";
// 解读
//(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)throwsSQLException {
* 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<Actor> list =
* queryRunner.query(connection, sql, new BeanListHandler<>(Actor.class), 1);
* System.out.println("输出集合的信息");
* for (Actor actor : list) {
* System.out.print(actor);
* }
* //释放资源
* JDBCUtilsByDruid.close(null, null, connection);
* }
*/
List<Actor> list =
queryRunner.query(connection, sql, new BeanListHandler<>(Actor.class), 1);
System.out.println("输出集合的信息");
for (Actor actor : list) {
System.out.print(actor);
}
//释放资源
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 actor where id = ?";
// 老韩解读
// 因为我们返回的单行记录<--->单个对象 , 使用的 Hander 是 BeanHandler
Actor actor = queryRunner.query(connection, sql, new BeanHandler<>(Actor.class), 10);
System.out.println(actor);
// 释放资源
JDBCUtilsByDruid.close(null, null, connection);
}
//演示 apache-dbutils + druid 完成查询结果是单行单列-返回的就是 object
@Test
public void testScalar() throws SQLException {
//1. 得到 连接 (druid)
Connection connection = JDBCUtilsByDruid.getConnection();
//2. 使用 DBUtils 类和接口 , 先引入 DBUtils 相关的 jar , 加入到本 Project
//3. 创建 QueryRunner
QueryRunner queryRunner = new QueryRunner();
//4. 就可以执行相关的方法,返回单行单列 , 返回的就是 Object
String sql = "select name from actor where id = ?";
//老师解读: 因为返回的是一个对象, 使用的 handler 就是 ScalarHandler
Object obj = queryRunner.query(connection, sql, new ScalarHandler(), 4);
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 actor where id = ?";
// 解读
//(1) 执行 dml 操作是 queryRunner.update()
//(2) 返回的值是受影响的行数 (affected: 受影响)
//int affectedRow = queryRunner.update(connection, sql, "林青霞", "女", "1966-10-10", "116");
int affectedRow = queryRunner.update(connection, sql, 1000);
System.out.println(affectedRow > 0 ? "执行成功" : "执行没有影响到表");
// 释放资源
JDBCUtilsByDruid.close(null, null, connection);
}
}
先分析一个问题
apache-dbutils+ Druid 简化了JDBC开发,但还有不足:
SQL语句是固定,不能通过参数传入,通用性不好,需要进行改进,更方便执行增删改查
对于select 操作,如果有返回值,返回类型不能固定,需要使用泛型
将来的表很多,业务需求复杂,不可能只靠一个Java类完成
引出=》 BasicDAO画出示意图
基本说明
BasicDAO 应用实例
完成一个简单设计
com.zwj.dao_.utils //工具类
com.zwj.dao_.domain //javabean
com.zwj.dao_.dao //存放XxxDAO和BasicDAO_
com.zwj.dao_.test //写测试类
package com.zwj.dao_.dao;
/**
* 开发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);
}
}
}
package com.zwj.dao_.dao;
import com.zwj.dao_.domain.Actor;
public class ActorDAO extends BasicDAO<Actor> {
//1. 就有 BasicDAO 的方法
//2. 根据业务需求,可以编写特有的方法.
}
package com.zwj.dao_.test;
import com.zwj.dao_.dao.ActorDAO;
import com.zwj.dao_.domain.Actor;
import org.junit.jupiter.api.Test;
import java.util.List;
public class TestDAO {
//测试ActorDAO 对actor表crud操作
@Test
public void testActorDAO() {
ActorDAO actorDAO = new ActorDAO();
//1. 查询
List<Actor> actors = actorDAO.queryMulti("select * from actor where id >= ?", Actor.class, 1);
System.out.println("===查询结果===");
for (Actor actor : actors) {
System.out.println(actor);
}
//2. 查询单行记录
Actor actor = actorDAO.querySingle("select * from actor where id = ?", Actor.class, 6);
System.out.println("====查询单行结果====");
System.out.println(actor);
//3. 查询单行单列
Object o = actorDAO.queryScalar("select name from actor where id = ?", 6);
System.out.println("====查询单行单列值===");
System.out.println(o);
//4. dml操作 insert ,update, delete
int update = actorDAO.update("insert into actor values(null, ?, ?, ?, ?)", "张无忌", "男", "2000-11-11", "999");
System.out.println(update > 0 ? "执行成功" : "执行没有影响表");
}
}
转载自: https://www.cnblogs.com/wenjie2000/p/16724862.html