目录
基本介绍
JDBC带来的好处
JDBC API
JDBC程序编写步骤
快速入门案例
JDBC连接五种方式
提示
ResultSet数据集
基本介绍
Statement
基本介绍
PreparedStatement
基本介绍
预处理好处
JDBC API
事务
基本结束
批处理
基本介绍
数据库连接池
传统获取Connection问题分析
数据库连接池基本介绍
数据库连接池示意图
数据库连接池种类
C3P0连接数据库
Druid(德鲁伊)连接数据库
将JDBCUtils工具类 改成Druid(德鲁伊)实现
Apache -DBUtils
先分析一个问题
示意图
基本介绍
DbUtils类
表和JavaBean 的类型映射关系
DAO和增删改查通用方法-BasicDao
先分析一个问题
基本说明
基本介绍
- JDBC为访问不同数据库提供了统一的接口,为使用者屏蔽了细节问题。
- Java程序员使用JDBC,可以连接任何提供了JDBC驱动程序的数据库系统,从而完成对数据的各种操作。
- JDBC的基本原理图
JDBC带来的好处
- JDBC带来都好处
- 说明:JDBC是Java提供一套用于数据库操作的接口API, Java程序员只需要面向这套接口即可。不同的数据库厂商,需要针对这套接口,提供不同实现。
JDBC API
- JDBC API是一系列的接口,它统一和规范了应用程序与数据库的连接,执行SQL语句,并到得到返回结果等各类操作,相关类和接口在java.sql与javax.sql包中
JDBC程序编写步骤
- 注册驱动-加载Driver
- 获取连接-得到Connection
- 执行增删改查-发送SQL给mysql执行
- 释放资源-关闭相关的连接
快速入门案例
package chapter25.mysql;
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对象 旧驱动
com.mysql.cj.jdbc.Driver driver = new com.mysql.cj.jdbc.Driver();//创建driver对象 新版驱动 不使用会警告
//2.得到连接
//说明
//(1)jdbc:mysql:// 规定好表示协议 通过jdbc的方式连接mysql
//(2)localhost 主机,可以是ip地址
//(3)3306 表示mysql 监听的端口
//(4)db02 表示连接到mysql dbms 的那个数据库
String url="jdbc:mysql://localhost:3306/db02";
//将 用户名和密码放入到Properties对象
Properties properties = new Properties();
//说明 user 和 password 是规定好的 后面的值根据实际情况写
properties.setProperty("user","root"); //用户
properties.setProperty("password","root"); //密码
//获取连接
Connection connect = driver.connect(url, properties);
//3.执行sql
// String sql="insert into actor values(5,'刘德华','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 ?"成功":"失败");
//关闭连接
statement.close();
connect.close();
}
}
JDBC连接五种方式
package chapter25.mysql;
import com.mysql.cj.jdbc.Driver;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcConn {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
connect05();
}
//方式1
public static void connect01() throws SQLException {
Driver driver = new Driver();
String url="jdbc:mysql://localhost:3306/db02";
Properties properties = new Properties();
properties.setProperty("user","root"); //用户
properties.setProperty("password","root");
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
//方式2
public void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
//使用反射加载Driver类 动态加载 更加灵活 减少依赖性
Class> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver =(Driver) aClass.newInstance();
String url="jdbc:mysql://localhost:3306/db02";
Properties properties = new Properties();
properties.setProperty("user","root"); //用户
properties.setProperty("password","root");
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
//方式3 使用 DriverManager 替代 Diver 进行统一管理
public static void connect03() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
//使用反射加载Driver
Class> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver =(Driver) aClass.newInstance();
//创建 url 和 user 和password
String url="jdbc:mysql://localhost:3306/db02";
String user="root";
String password="root";
DriverManager.registerDriver(driver); //注册Driver驱动
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//方式4:使用Class.forName 自动完成注册驱动,简化代码
//这种方式 开发过程中用的最多的
public static void connect04() throws ClassNotFoundException, SQLException {
//使用反射加载了 Driver类
//在加载 Driver类 完成注册
Class.forName("com.mysql.cj.jdbc.Driver");
//创建 url 和 user 和password
String url="jdbc:mysql://localhost:3306/db02";
String user="root";
String password="root";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//方式5: 在方式4的基础上改进 增加配置文件 让连接mysql更加灵活
public static void connect05() throws IOException, ClassNotFoundException, SQLException {
//通过Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("E:\BCSP_S2\Java\Java_codes\extracurricular\src\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
Class.forName("com.mysql.cj.jdbc.Driver"); //建议写上
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}
提示
- mysql驱动5.16可以无需class.forName(“com.mysql.jdbc.Driver”);
- 从JDK1.5以后使用了jdbc4,不需要显示调用class.forName()注册驱动而是自动调用驱动 jar包下META-INFservicesjava.sql.Driver 文本中的类名称去注册
- 建议还是写上Class.forName(“com.mysql.jdbc.Driver”),更加明确
package chapter25.mysql;
import com.mysql.cj.jdbc.Driver;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcConn {
public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException {
connect05();
}
//方式1
public static void connect01() throws SQLException {
Driver driver = new Driver();
String url="jdbc:mysql://localhost:3306/db02";
Properties properties = new Properties();
properties.setProperty("user","root"); //用户
properties.setProperty("password","root");
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
//方式2
public void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
//使用反射加载Driver类 动态加载 更加灵活 减少依赖性
Class> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver =(Driver) aClass.newInstance();
String url="jdbc:mysql://localhost:3306/db02";
Properties properties = new Properties();
properties.setProperty("user","root"); //用户
properties.setProperty("password","root");
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
//方式3 使用 DriverManager 替代 Diver 进行统一管理
public static void connect03() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
//使用反射加载Driver
Class> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver =(Driver) aClass.newInstance();
//创建 url 和 user 和password
String url="jdbc:mysql://localhost:3306/db02";
String user="root";
String password="root";
DriverManager.registerDriver(driver); //注册Driver驱动
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//方式4:使用Class.forName 自动完成注册驱动,简化代码
//这种方式 开发过程中用的最多的
public static void connect04() throws ClassNotFoundException, SQLException {
//使用反射加载了 Driver类
//在加载 Driver类 完成注册
Class.forName("com.mysql.cj.jdbc.Driver");
//创建 url 和 user 和password
String url="jdbc:mysql://localhost:3306/db02";
String user="root";
String password="root";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//方式5: 在方式4的基础上改进 增加配置文件 让连接mysql更加灵活
public static void connect05() throws IOException, ClassNotFoundException, SQLException {
//通过Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("E:\BCSP_S2\Java\Java_codes\extracurricular\src\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
Class.forName("com.mysql.cj.jdbc.Driver"); //建议写上
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}
提示
- mysql驱动5.16可以无需class.forName(“com.mysql.jdbc.Driver”);
- 从JDK1.5以后使用了jdbc4,不需要显示调用class.forName()注册驱动而是自动调用驱动 jar包下META-INFservicesjava.sql.Driver 文本中的类名称去注册
- 建议还是写上Class.forName(“com.mysql.jdbc.Driver”),更加明确
ResultSet数据集
基本介绍
- 表示数据库结果集的数据表,通常通过执行查询数据库的语句生成
- ResultSet对象保持一个光标指向其当前的数据行。最初,光标位于第一行之前
- next方法将光标移动到下一行,并且由于ResultSet对象中没有更多行时返回false,因此可以在while循环中使用循环遍历结果集。
package chapter25.resultset_;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class ResultSet_ {
public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
//通过Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("E:\BCSP_S2\Java\Java_codes\extracurricular\src\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//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 ,borndate,phone from actor";
//执行给定的SQL语句,该语句返回单个 ResultSet对象
ResultSet resultSet = statement.executeQuery(sql);
//5.使用while取出数据
while (resultSet.next()){ //next方法向下移动 如果没有更多行 则返回false
int id = resultSet.getInt(1); //获取该行的第1列
String name = resultSet.getString(2); //获取该行的第2列
Date date = resultSet.getDate(3); //获取该行的第3列
String phone = resultSet.getString(4); //获取该行的第4列
System.out.println(id+"t"+name+"t"+date+"t"+phone);
}
//6.关闭连接
resultSet.close();
statement.close();
connection.close();
}
}
- 表示数据库结果集的数据表,通常通过执行查询数据库的语句生成
- ResultSet对象保持一个光标指向其当前的数据行。最初,光标位于第一行之前
- next方法将光标移动到下一行,并且由于ResultSet对象中没有更多行时返回false,因此可以在while循环中使用循环遍历结果集。
package chapter25.resultset_;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class ResultSet_ {
public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
//通过Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("E:\BCSP_S2\Java\Java_codes\extracurricular\src\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//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 ,borndate,phone from actor";
//执行给定的SQL语句,该语句返回单个 ResultSet对象
ResultSet resultSet = statement.executeQuery(sql);
//5.使用while取出数据
while (resultSet.next()){ //next方法向下移动 如果没有更多行 则返回false
int id = resultSet.getInt(1); //获取该行的第1列
String name = resultSet.getString(2); //获取该行的第2列
Date date = resultSet.getDate(3); //获取该行的第3列
String phone = resultSet.getString(4); //获取该行的第4列
System.out.println(id+"t"+name+"t"+date+"t"+phone);
}
//6.关闭连接
resultSet.close();
statement.close();
connection.close();
}
}
Statement
基本介绍
- Statement对象 用于执行静态SQL语句并返回其生成的结果的对象
- 在连接建立后 ,需要对数据库进行访问,执行 命名或是SQL语句,可以通过
- Statement [存在SQL注入问题]
- PreparedStatement [预处理]
- CallableStatement [存储过程]
- Srarement对象执行SQL 语句,存在SQL注入风险
- SQL注入是利用某些系统没有对用户输入的数据进行充分的检查,而是用户输入数据中注入非法的SQL 语句段或命令,恶意攻击数据库。
- 要防范 SQL 注入,只要用 PreparedStatement(从Statement扩展而来)取代 Statement 就可以了
- Statement对象 用于执行静态SQL语句并返回其生成的结果的对象
- 在连接建立后 ,需要对数据库进行访问,执行 命名或是SQL语句,可以通过
- Statement [存在SQL注入问题]
- PreparedStatement [预处理]
- CallableStatement [存储过程]
- Srarement对象执行SQL 语句,存在SQL注入风险
- SQL注入是利用某些系统没有对用户输入的数据进行充分的检查,而是用户输入数据中注入非法的SQL 语句段或命令,恶意攻击数据库。
- 要防范 SQL 注入,只要用 PreparedStatement(从Statement扩展而来)取代 Statement 就可以了
PreparedStatement
基本介绍
- PreparedStatement 执行的 SQL 语句中的参数用问号(?)来表示,调用PreparedStatement对象的 setXxx()方法来设置这些参数。setXxx()方法有两个参数,第一个参数是要设置的SQL 语句中的参数的索引(从 1开始),第二个是设置SQL 语句中的参数值
- 调用 executeQuery(),返回 ResultSet 对象
- 调用 executeUpdate():执行更新,包括增 删 修改
预处理好处
- 不再使用+拼接sql语句,减少语法错误
- 有效的解决了sql注入问题
- 大大减少了编译次数,效率更高
package com.hspedu.jdbc.preparedstatement_;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;
@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();
}
}
JDBC API
事务
基本结束
- JDBC程序中当一个Connection对象创建时,默认情况下是自动提交事务:每次执行一个SQL语句,如果执行成功,就会向数据库自动提交,而且不能回滚。
- JDBC程序中为了让多个SQL语句作为一个整体执行,需要使用事务
- 调用 Connection 的 setAutoCommit(false) 可以取消自动提交事务
- 在所有的SQL 语句都成功执行后, 调用Connection 的 commit();方法提交事务
- 在其中某个操作失败或出现异常时, 调用Connection 的 rollback(); 方法回滚事务
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;
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(); // 执行第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);
}
}
}
- JDBC程序中当一个Connection对象创建时,默认情况下是自动提交事务:每次执行一个SQL语句,如果执行成功,就会向数据库自动提交,而且不能回滚。
- JDBC程序中为了让多个SQL语句作为一个整体执行,需要使用事务
- 调用 Connection 的 setAutoCommit(false) 可以取消自动提交事务
- 在所有的SQL 语句都成功执行后, 调用Connection 的 commit();方法提交事务
- 在其中某个操作失败或出现异常时, 调用Connection 的 rollback(); 方法回滚事务
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;
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(); // 执行第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的批量处理语句包括下面方法:
- 当需要成批插入或者更新记录时。可以采用Java的批量更新机制,者一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。
- JDBC的批量处理语句包括下面方法:
addBatch():添加需要批量处理的SQL语句或参数
executeBatch():执行批量处理语句
clearBatch():清空批处理包的语句
- JDBC连接MySQL时,如果要使用批处理功能,请再url中加参数?rewriteBatchedStatements=true
- 批处理往往和PreparedStatement一起搭配使用,可以既减少编译次数,又能减少运行次数,效率大大提高
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;
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 语句加入到批处理包中 -> 看源码
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 数据库连接池, 速度快
- Drtid(德鲁伊)是阿里提供的数据库连接池,集DBCP.C3P0, Proxool有点于一身的数据库连接池
C3P0连接数据库
package chapter25.datasoure;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class C3P0_ {
public static void main(String[] args) throws SQLException {
testC3P0_02();
}
//方式1: 相关参数,在程序中指定 user url password 等
public static void testC3P0_01() throws Exception {
//1.创建一个数据源对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//2. 通过配置文件 mysql.Properties 获取相关配置信息
Properties properties = new Properties();
//加载相关信息
properties.load(new FileInputStream("E:\BCSP_S2\Java\Java_codes\extracurricular\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);
long l = System.currentTimeMillis();
//测试连接池的效率 测试连接mysql 5000次操作
for (int i = 0; i < 5000; i++) {
Connection connection = comboPooledDataSource.getConnection();//这个方法就是从 DataSource 接口实现的
// System.out.println("连接ok");
connection.close();
}
long l1 = System.currentTimeMillis();
System.out.println(l1 - l);
}
//第二种方式 使用配置文件模板来完成
//1.将c3p0 提供的 c3p0.config.xml 拷贝到 src目录下
//2. 该文件指定了连接数据库和连接池的相关参数
public static void testC3P0_02() throws SQLException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("hello");
long l = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
Connection connection = comboPooledDataSource.getConnection();
// System.out.println("连接成功");
connection.close();
}
long l1 = System.currentTimeMillis();
System.out.println(l1 - l);
}
}
Druid(德鲁伊)连接数据库
package chapter25.datasoure;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLOutput;
import java.util.Properties;
public class Druid_ {
public static void main(String[] args) {
try {
testDruid();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void testDruid() throws Exception {
//1.加入 Druid jar 包
//2. 加入配置文件 ,将该文件拷贝项目的src目录
//3.创建Properties对象,读取配置文件
Properties properties = new Properties();
//加载配置文件信息
properties.load(new FileInputStream("E:\BCSP_S2\Java\Java_codes\extracurricular\src\druid.properties"));
//4.创建 一个指定参数的数据库连接池 Druid连接池 DruidDataSourceFactory 数据源工厂
long l = System.currentTimeMillis();
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
for (int i = 0; i < 5000; i++) {
Connection connection = dataSource.getConnection();
// System.out.println("连接成功");
connection.close();
}
long l1 = System.currentTimeMillis();
System.out.println(l1-l);
}
}
将JDBCUtils工具类 改成Druid(德鲁伊)实现
package chapter25.datasoure;
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;
public class JDBCUtilsByDruid {
private static DataSource ds;
//在静态代码块完成 ds初始化
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("E:\BCSP_S2\Java\Java_codes\extracurricular\src\druid.properties"));
ds= DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//编写getConnection方法
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//关闭连接 ,再次强调: 在数据库连接池技术中,colse 不是真的断掉连接
//而是把使用的 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);
}
}
}
package chapter25.datasoure;
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;
public class JDBCUtilsByDruid {
private static DataSource ds;
//在静态代码块完成 ds初始化
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("E:\BCSP_S2\Java\Java_codes\extracurricular\src\druid.properties"));
ds= DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//编写getConnection方法
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//关闭连接 ,再次强调: 在数据库连接池技术中,colse 不是真的断掉连接
//而是把使用的 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);
}
}
}
Apache -DBUtils
先分析一个问题
- 关闭connection 后 resultSet 结果集无法使用
- resultSet 不利于数据的管理
示意图
- 关闭connection 后 resultSet 结果集无法使用
- resultSet 不利于数据的管理
示意图
基本介绍
- commons-dbutils 是 Apache 组织提供的一个开源 JDBC工具类库 ,它是对JDBC的封装,使用dbutils能极大简化jdbc编码的工作量。
DbUtils类
- QueruRunner类:该类封装了SQL的执行,是线程安全的,可以实现增 ,删,改,查,批处理
- 使用QueryRunner类实现查询
- ResultSetHandler接口:该接口用于处理 Java.sql.ResultSet,将数据按要求转换成另一种形式。
- ArrayHandler:把结果集中的第一行数据转成对象数组
- ArrayListHandler:把结果集中的第一行数据封装到一个对应的JavaBean实例中,存放List里。
- ColumnListHandler:将结果集中某一列的数据存放到List中
- KeyedHandler(name):将结果集中的每行数据都封装到Map里,再把这些map在存放到一个map里,其中key为指定的key。
- MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
- QueruRunner类:该类封装了SQL的执行,是线程安全的,可以实现增 ,删,改,查,批处理
- 使用QueryRunner类实现查询
- ResultSetHandler接口:该接口用于处理 Java.sql.ResultSet,将数据按要求转换成另一种形式。
- ArrayHandler:把结果集中的第一行数据转成对象数组
- ArrayListHandler:把结果集中的第一行数据封装到一个对应的JavaBean实例中,存放List里。
- ColumnListHandler:将结果集中某一列的数据存放到List中
- KeyedHandler(name):将结果集中的每行数据都封装到Map里,再把这些map在存放到一个map里,其中key为指定的key。
- MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。
package chapter25.datasoure;
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;
public class DBUtils_USE {
public static void main(String[] args) {
try {
testScalar();
} catch (SQLException e) {
e.printStackTrace();
}
}
//使用apache-DBUtils 工具类 + druid 完成对表的crud操作 -多行数据
public static void testQueryMany() throws SQLException { //返回结果的多行的情况
//1.得到连接
Connection connection = JDBCUtilsByDruid.getConnection();
//2.使用 DBUtils 类和接口 ,先引入DBUtils 相关的jar文件 , 加入到本Project
//3.创建 QueryRunner
QueryRunner queryRunner = new QueryRunner();
//4.就可以执行相关的方法,返回ArrayList 结果集
String sql="select * from actor where id>?";
//解读
//(1): query 方法就是执行sql 语句 ,得到resultset ---封装到----->ArrayList 集合中
//(2) 返回集合
//(3) connection: 连接
//(4) 执行的sql语句
//(5) new BeanListHandler<>(Actor.class):在将resultest ---> Actor对象->封装到 ArrayList中
// 底层使用反射机制 去获取 Actor 类的属性,然后进行封装
//(6) 1就是给 sql 语句中的 ?赋值 ,可以有多个值,因为是可变参数 Object...params
//(7) 底层得到的resultset ,会在 query 关闭 关闭PreparedStatment
List list=
queryRunner.query(connection, sql, new BeanListHandler<>(Actor.class), 1);
for (Actor actor:list){
System.out.println(actor);
}
//释放资源
JDBCUtilsByDruid.close(null,null,connection);
}
//使用apache-DBUtils 工具类 + druid 完成对表的crud操作 -单行多列数据
public static void testQuerySingle() throws Exception {
//1.得到连接(druid)
Connection connection = JDBCUtilsByDruid.getConnection();
//2.创建 QueryRunner
QueryRunner queryRunner = new QueryRunner();
//3.定义sql语句
String sql="select * from actor where id=?";
//4.因为我们返回的单行记录<--->单个对象,使用的Hander 是 BeanHandler
Actor query = queryRunner.query(connection, sql, new BeanHandler<>(Actor.class), 6);
System.out.println(query);
//5.释放资源
JDBCUtilsByDruid.close(null,null,connection);
}
//使用apache-DBUtils 工具类 + druid 完成查询结果是单行单列的-返回的就是Object对象
public static void testScalar() throws SQLException {
//1.得到连接(druid)
Connection connection = JDBCUtilsByDruid.getConnection();
//2.创建 QueryRunner
QueryRunner queryRunner = new QueryRunner();
//3.定义sql语句
String sql="select name from actor where id=?";
Object obj = queryRunner.query(connection, sql, new ScalarHandler(), 6);
System.out.println(obj);
}
}
package chapter25.datasoure;
import org.apache.commons.dbutils.QueryRunner;
import java.sql.Connection;
import java.sql.SQLException;
public class DBUtils_DML {
public static void main(String[] args) {
try {
testDML();
} catch (SQLException e) {
e.printStackTrace();
}
}
使用apache-DBUtils 工具类 + druid 完成 dml (update,insert,delete)
public static void testDML() throws SQLException {
//1.得到连接(druid)
Connection connection = JDBCUtilsByDruid.getConnection();
//2.创建 QueryRunner
QueryRunner queryRunner = new QueryRunner();
//3.定义sql语句 完成 update insert delete
// String sql="update actor set name=? where id=?"; //修改
// String sql ="insert into actor values(50,?,?,?)"; //新增
String sql="delete from actor where id=?";
//说明:
//(1) 执行 dml 操作是 querRunner.update
//(2) 返回的值是受影响的行数 (affected:受影响)
int affectedRow = queryRunner.update(connection, sql, 500);
System.out.println(affectedRow>0 ? "执行成功":"执行没有影响到表");
//5.释放资源
JDBCUtilsByDruid.close(null,null,connection);
}
}



