前置工作:
下载jar包:http://dev.mysql.com/downloads/connector/j/
解压后得到jar包
放在项目lib文件夹下
右键–Add as Library
public class jdbcFirstDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//前置工作: 在项目下创建一个文件夹比如 libs
//将 mysql.jar 拷贝到该目录下,点击 add to project ..加入到项目中
//1.加载驱动(注册驱动)
Class.forName("com.mysql.cj.jdbc.Driver"); //反射-->动态加载
//底层:
/*
源码: 1. 静态代码块,在类加载时,会执行一次.
2. DriverManager.registerDriver(new Driver());
3. 因此注册driver的工作已经完成
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
*/
//2.用户信息和URL
//(1) jdbc:mysql:// 规定好表示协议,通过jdbc的方式连接mysql
//(2) localhost 主机,可以是ip地址
//(3) 3306 表示mysql监听的端口
//(4) db03 连接到mysql dbms 的哪个数据库
//(5) mysql的连接本质就是前面学过的socket连接
String url = "jdbc:mysql://localhost:3306/db03?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
String username = "root";
String password = "1234";
//3.连接数据库对象 Connection代表数据库
Connection connection = DriverManager.getConnection(url, username, password);
//4.执行SQL,根据不同的语句得到不同的返回结果(DML--int , DQL--ResultSet)
//更新语句(如果是dml语句,返回的就是影响的行数,= 0即执行失败
//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";
int rows = statement.executeUpdate(sql)
//5.释放连接
resultSet.close();
statement.close();
connection.close();
}
}
/**
* @author 韩顺平
* @version 1.0
* 分析java 连接mysql的常用2种方式
*/
public class JdbcConn {
//方式1: 使用Class.forName 自动完成注册驱动,简化代码
//这种方式获取连接是使用的最多,推荐使用
@Test
public void connect04() throws ClassNotFoundException, SQLException {
//使用反射加载了 Driver类
//在加载 Driver类时,完成注册
/*
源码: 1. 静态代码块,在类加载时,会执行一次.
2. DriverManager.registerDriver(new Driver());
3. 因此注册driver的工作已经完成
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
*/
Class.forName("com.mysql.cj.jdbc.Driver");
//创建url 和 user 和 password
String url = "jdbc:mysql://localhost:3306/db03?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
String user = "root";
String password = "hsp";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第4种方式~ " + connection);
}
//方式2 , 在方式1的基础上改进,增加配置文件,让连接mysql更加灵活
//配置文件见后面
@Test
public void connect05() throws IOException, ClassNotFoundException, SQLException {
//通过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);
}
}
方式1:
建议还是写上 Class.forName("com.mysql.cj.jdbc.Driver")
方式2配置文件:
user=root
password=hsp
url=jdbc:mysql://localhost:3306/db03?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
driver=com.mysql.jdbc.cj.Driver
光标向上移:next
光标向下移:previous
/**
* 演示select 语句返回 ResultSet ,并取出结果
*/
@SuppressWarnings({"all"})
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();
}
}
ResultSet接口,底层实际类型:JDBC42ResultSet(它是mysql实现ResultSet接口的类)
ResultSet->rowData->rows->
elementData->0\1\2行数据->internalRowData真正存放数据的字节数组
/**
* @author 韩顺平
* @version 1.0
* 演示statement 的注入问题
*/
@SuppressWarnings({"all"})
public class Statement_ {
public static void main(String[] args) throws Exception {
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. 得到Statement
Statement statement = connection.createStatement();
//4. 组织SqL
String sql = "select name , pwd from admin where name ='"
+ admin_name + "' and pwd = '" + admin_pwd + "'";
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()) { //如果查询到一条记录,则说明该管理存在
System.out.println("恭喜, 登录成功");
} else {
System.out.println("对不起,登录失败");
}
//关闭连接
resultSet.close();
statement.close();
connection.close();
}
}
setXxx(int , ...)
,这个int
就是你需要设置的某个问号在整个sql语句是第几个问号-1
① 处理SQL注入的问题
注意:
//创建prepareStatement对象
PrepareStatement prepareStatement = connection.prepareStatement(sql);
//也就是说,sql必须写在prepareStatement的构造器里
//后面executeQuery()时不要再填写sql,因为上面语句已经给prepareStatement处理过了
//相当于把上面还没有替换?的语句复制下来了,系统不知道这个?是什么
ResultSet resultSet = preparedStatement.executeQuery(sql); //相当于↓
ResultSet resultSet = preparedStatement.executeQuery(select name , pwd from admin where name =? and pwd = ?); //报错
//一定要用,只能在一开始定义sql的时候就没有问号
/**
* @author 韩顺平
* @version 1.0
* 演示PreparedStatement使用
*/
@SuppressWarnings({"all"})
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();
}
}
② 预处理DML
/**
* @author 韩顺平
* @version 1.0
* 演示PreparedStatement使用 dml语句
*/
@SuppressWarnings({"all"})
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();
}
}
package com.rxli;
import com.sun.xml.internal.ws.org.objectweb.asm.ClassAdapter;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.FileReader;
import java.sql.*;
import java.util.Properties;
public class JdbcTest {
public static void main(String[] args) throws Exception {
//加载properties
Properties properties = new Properties();
properties.load(new FileInputStream("src\\jdbc.properties"));
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String root = properties.getProperty("user");
String password = properties.getProperty("password");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, root, password);
// String sql = "INSERT INTO admin VALUES(?,?)";
// String sql = "UPDATE admin SET user = ? WHERE user = ?";
// String sql = "DELETE FROM admin WHERE user = ?";
String sql = "SELECT * FROM admin";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//==============1. 添加数据=================
// preparedStatement.setString(1, "tom");
// preparedStatement.setString(2, "123456");
//==============2. 修改数据=================
// preparedStatement.setString(1,"king");
// preparedStatement.setString(2,"tom");
//==============3. 删除数据=================
//preparedStatement.setString(1,"tom"); //tom被修改了,没有tom,删除失败
// preparedStatement.setString(1,"jack");
//================执行DML=================
// int rows = preparedStatement.executeUpdate();
// if(rows > 0) {
// System.out.println("操作成功");
// } else {
// System.out.println("操作失败");
// }
//================执行DQL=================
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
String user = resultSet.getString(1);
String pwd = resultSet.getString(2);
System.out.println("user=" + user + " pwd=" + pwd);
}
preparedStatement.close();
connection.close();
}
}
/**
* 这是一个工具类,完成 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");
} catch (IOException e) {
//在实际开发中,我们可以这样处理
//1. 将编译异常转成 运行异常
//2. 调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便.
//3. 因为编译异常必须要处理(要么写try-catch要么写throws),运行时异常可以按照默认处理(不写try-catch不写throws就默认是throws)
throw new RuntimeException(e);
}
}
//连接数据库, 返回Connection
public static Connection getConnection() {
try {
Class.forName(driver);
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
public class JDBCUtils_Use {
@Test
//dml
public void testDML() throws SQLException {
Connection connection = JDBCUtils.getConnection();
String sql = "update actor1 set name = ? where number = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,"小红");
preparedStatement.setString(2,"2020200");
int rows = preparedStatement.executeUpdate();
System.out.println(rows > 0 ? "成功":"失败");
JDBCUtils.close(null,preparedStatement,connection);
}
@Test
//查询
public void testQuery() throws SQLException {
Connection connection = JDBCUtils.getConnection();
String sql = "select name , sex from actor1 where number = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,"2020200");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
String name = resultSet.getString(1);
String sex = resultSet.getString(2);
System.out.println(name + "\t" + sex);
}
JDBCUtils.close(resultSet,preparedStatement,connection);
}
}
setAutoCommit(false)
commit()
rollback()
转账业务–>转出和接收必须是一个整体,要么同时成功要么同时失败
简化版
//==========================自动提交,不能回滚==========================
connection = JDBCUtils.getConnection(); // 在默认情况下,connection是默认自动提交
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate(); // 执行第1条sql
int i = 1 / 0; //抛出异常
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate(); // 执行第2条sql
//====================================================
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 (Exception e) {
//这里我们可以进行回滚,即撤销执行的SQL
//默认回滚到事务开始的状态.
System.out.println("执行发生了异常,撤销执行的sql");
try {
connection.rollback(); //回滚⭐
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
完整版:
package com.hspedu.jdbc.transaction_;
import com.hspedu.jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.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(); // 执行第2条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 (Exception e) {
//这里我们可以进行回滚,即撤销执行的SQL
//默认回滚到事务开始的状态.
System.out.println("执行发生了异常,撤销执行的sql");
try {
connection.rollback(); //回滚
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.close(null, preparedStatement, connection);
}
}
}
addBatch()
executeBatch()
clearBatch()
减少编译次数:因为PreparedStatement
对sql语句进行了预处理:
connection.prepareStatement(sql)
减少运行次数:把一次运行一个sql语句变成一次运行多个sql语句
package com.hspedu.jdbc.batch_;
import com.hspedu.jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.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);
}
//使用批量方式添加数据
//在这之前一定要给url加上rewriteBatchedStatements=ture
@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 语句加入到批处理包中⭐ -> 看源码
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);
}
}
//将sql 语句加入到批处理包中 -> 看源码
preparedStatement.addBatch();
/*
//1. 底层创建了一个ArrayList存放
//1. //第一就创建 ArrayList - elementData => Object[]对象数组
//2. elementData => Object[] 就会存放我们预处理的sql语句
//3. 当elementData满后,就按照1.5扩容(初始化10个-15-22个...)
//4. 当添加到指定的值后,就executeBatch
//5. 批量处理会减少我们发送sql语句的网络开销,而且减少编译次数,因此效率提高
public void addBatch() throws SQLException {
synchronized(this.checkClosed().getConnectionMutex()) {
//批处理数组是否为空,如果是,则新创建一个ArrayList,赋值给batchedArgs
if (this.batchedArgs == null) {
this.batchedArgs = new ArrayList();
}
//检查sql语句是否有问题
for(int i = 0; i < this.parameterValues.length; ++i) {
this.checkAllParametersSet(this.parameterValues[i], this.parameterStreams[i], i);
}
//在ArrayList下的elementDate存放预处理的sql语句
this.batchedArgs.add(new PreparedStatement.BatchParams(this.parameterValues, this.parameterStreams, this.isStream, this.streamLengths, this.isNull));
}
}
*/
连接同一个mysql的connection不能太多,不然baocuo–>too many connections
多次连接关闭connection,会导致程序特别慢
DataSource只是一个接口
下载C3P0
解压,找到jar包,拷贝到项目lib文件夹下
在C3P0高版本需要拷贝一个common辅助jar包
一定要加入到项目中:
选中右键->Add as library
/**
* 演示c3p0的使用
*/
public class C3P0_ {
//方式1: 相关参数,在程序中指定user, url , password等
@Test
public void testC3P0_01() throws Exception {
//1. 创建一个数据源对象comboPooledDataSource⭐
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//2. 通过配置文件mysql.properties 获取相关连接的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\jdbc.properties"));
//3. 读取相关的属性值
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
//4. 给数据源 comboPooledDataSource 设置相关的参数⭐
//注意:连接管理是由 comboPooledDataSource 来管理
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(user);
comboPooledDataSource.setPassword(password);
//5. 初始化连接数⭐(程序运行后,连接池自动存放10个已经连好的连接)
comboPooledDataSource.setInitialPoolSize(10);
//6. 最大连接数⭐(连接池最多能存放50个已经连好的连接,50个连接都用完,当第51个及后面的java程序来要连接时,会进入等待队列)
comboPooledDataSource.setMaxPoolSize(50);
//7. 测试连接池的效率, 测试对mysql 5000次操作
long start = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
// System.out.println(i);
//⭐这个方法是核心方法。就是从 DataSource 接口实现的
Connection connection = comboPooledDataSource.getConnection();
// System.out.println("连接OK");
connection.close();
}
long end = System.currentTimeMillis();
System.out.println("c3p0 5000连接mysql 耗时=" + (end - start));
}
//第二种方式 使用配置文件模板来完成
//1. 将c3p0 提供的 c3p0.config.xml 拷贝到 src根目录下
//2. 该文件指定了连接数据库和连接池的相关参数
@Test
public void testC3P0_02() throws SQLException {
//用配置文件给数据源 comboPooledDataSource 设置相关的参数⭐(ComboPooledDataSource(configName--自己设的))
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("c3p0_test");
//测试5000次连接mysql
long start = System.currentTimeMillis();
System.out.println("开始执行....");
for (int i = 0; i < 5000000; i++) {
Connection connection = comboPooledDataSource.getConnection();
//System.out.println("连接OK~");
connection.close();
}
long end = System.currentTimeMillis();
System.out.println("c3p0的第二种方式(500000) 耗时=" + (end - start));//13997
}
}
c3p0-config.xml
一定一定要放在src根目录下!!!
<c3p0-config>
<named-config name="c3p0_test">
<property name="driverClass">com.mysql.cj.jdbc.Driverproperty>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db01?serverTimezone=UTCproperty>
<property name="user">rootproperty>
<property name="password"> property>
<property name="acquireIncrement">5property>
<property name="initialPoolSize">10property>
<property name="minPoolSize">5property>
<property name="maxPoolSize">50property>
<property name="maxStatements">5property>
<property name="maxStatementsPerConnection">2property>
named-config>
c3p0-config>
在src根目录下创建一个druid.properties
# druid.properties文件的配置
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db01?serverTimezone=UTC
username=root
password=
# 初始化连接数量
initialSize=10
# 最大连接数
maxActive=50
# 最小连接数(min idle connection size)
minIdle=5
# 最大等待时间(在java程序里最多等待的毫秒数)
maxWait=3000
/**
* 测试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 < 5000000; i++) {
Connection connection = dataSource.getConnection();
//System.out.println(connection.getClass());
//System.out.println("连接成功!");
connection.close();
}
long end = System.currentTimeMillis();
System.out.println("druid连接池 操作500000 耗时=" + (end - start));//1456
}
}
注意,在数据库连接池技术中,close不是真的断掉连接!
而是把使用的Connection对象放回连接池
因为connection是一个接口
之前JDBCUtil是MySQL中的实际运行类型JDBC4Connection
实现的close方法,关闭连接
现在JDBCUtilsByDruid是druid中实际运行类型DruidPooledConnection
实现的close方法,是关闭引用,将connection放回连接池
也就是说,这里因为有动态绑定机制
,所以真正的实现并不相同
conection是个接口 mysql厂商和阿里巴巴厂商实现了这个接口 但实现接口的方法不通mysql是直接把连接关闭 德鲁伊是把引用的连接放回到连接池等待下一次引用 是这个意思吗 感觉懵懵懂懂的
/**
* 基于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);
}
}
}
通过德鲁伊数据库连接池获取连接对象
@SuppressWarnings({"all"})
public class JDBCUtilsByDruid_USE {
@Test
public void testSelect() {
System.out.println("使用 druid方式完成");
//1. 得到连接
Connection connection = null;
//2. 组织一个sql
String sql = "select * from actor where id >= ?";
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, 1);//给?号赋值
//执行, 得到结果集
set = preparedStatement.executeQuery();
//遍历该结果集
while (set.next()) {
int id = set.getInt("id");
String name = set.getString("name");//getName()
String sex = set.getString("sex");//getSex()
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 {
//关闭资源
JDBCUtilsByDruid.close(set, preparedStatement, connection);
}
}
//使用老师的土方法来解决ResultSet =封装=> Arraylist
@Test
public ArrayList<Actor> testSelectToArrayList() {
System.out.println("使用 druid方式完成");
//1. 得到连接
Connection connection = null;
//2. 组织一个sql
String sql = "select * from actor where id >= ?";
PreparedStatement preparedStatement = null;
ResultSet set = null;
ArrayList<Actor> list = new ArrayList<>();//创建ArrayList对象,存放actor对象
//3. 创建PreparedStatement 对象
try {
connection = JDBCUtilsByDruid.getConnection();
System.out.println(connection.getClass());//运行类型 com.alibaba.druid.pool.DruidPooledConnection
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 1);//给?号赋值
//执行, 得到结果集
set = preparedStatement.executeQuery();
//遍历该结果集
while (set.next()) {
int id = set.getInt("id");
String name = set.getString("name");//getName()
String sex = set.getString("sex");//getSex()
Date borndate = set.getDate("borndate");
String phone = set.getString("phone");
//把得到的resultset 的记录,封装到 Actor对象,放入到list集合
list.add(new Actor(id, name, sex, borndate, phone));
}
System.out.println("list集合数据=" + list);
for(Actor actor : list) {
System.out.println("id=" + actor.getId() + "\t" + actor.getName());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtilsByDruid.close(set, preparedStatement, connection);
}
//因为ArrayList 和 connection 没有任何关联,所以该集合可以复用.
return list;
}
}
package com.hspedu.jdbc.datasource;
import org.junit.jupiter.api.Test;
import java.sql.*;
import java.util.ArrayList;
@SuppressWarnings({"all"})
public class JDBCUtilsByDruid_USE {
//使用老师的土方法来解决ResultSet =封装=> Arraylist
@Test
public ArrayList<Actor> testSelectToArrayList() {
System.out.println("使用 druid方式完成");
//1. 得到连接
Connection connection = null;
//2. 组织一个sql
String sql = "select * from actor where id >= ?";
PreparedStatement preparedStatement = null;
ResultSet set = null;
ArrayList<Actor> list = new ArrayList<>();//创建ArrayList对象,存放actor对象
//3. 创建PreparedStatement 对象
try {
connection = JDBCUtilsByDruid.getConnection();
System.out.println(connection.getClass());//运行类型 com.alibaba.druid.pool.DruidPooledConnection
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 1);//给?号赋值
//执行, 得到结果集
set = preparedStatement.executeQuery();
//遍历该结果集
while (set.next()) {
int id = set.getInt("id");
String name = set.getString("name");//getName()
String sex = set.getString("sex");//getSex()
Date borndate = set.getDate("borndate");
String phone = set.getString("phone");
//把得到的resultset 的记录,封装到 Actor对象,放入到list集合⭐⭐
list.add(new Actor(id, name, sex, borndate, phone));
}
System.out.println("list集合数据=" + list); //记得重写toString
//用增强for循环调用,list对象一直在,即使connection关闭了也有
for(Actor actor : list) {
System.out.println("id=" + actor.getId() + "\t" + actor.getName());
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtilsByDruid.close(set, preparedStatement, connection);
}
//因为ArrayList 和 connection 没有任何关联,所以该集合可以复用.
return list;
}
}
commons-dbutils
QueryRunner
ResultHander
下载jar包
@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 和PreparedStatment,会在 query 关闭⭐⭐ -->看源码
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);
}
}
/**
* 分析 queryRunner.query方法:
* public T query(Connection conn, String sql, ResultSetHandler 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 经过handle处理--> arrayList[result] [使用到反射,对传入Actor.class对象处理]
* } catch (SQLException var33) {
* this.rethrow(var33, sql, params);
* } finally {
* try {
* this.close(rs);//关闭resultset
* } finally {
* this.close((Statement)stmt);//关闭preparedstatement对象
* }
* }
*
* return result;
* }
*/
@SuppressWarnings({"all"})
public class DBUtils_USE {
//演示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);
}
}