文章和代码曾经归档至【Github仓库:https://github.com/timerring/java-tutorial 】或者公众号【AIShareLab】回复 java 也可获取。
JDBC 概述
根本介绍
- JDBC为拜访不同的数据库提供了对立的接口,为使用者屏蔽了细节问题。
- Java程序员应用JDBC,能够连贯任何提供了JDBC驱动程序的数据库系统,从而实现对数据库的各种操作。
- JDBC的基本原理图[重要!]
模仿JDBC
package com.hspedu.jdbc.myjdbc;
/**
* 咱们规定的jdbc接口(办法)
*/
public interface JdbcInterface {
//连贯
public Object getConnection() ;
//crud
public void crud();
//敞开连贯
public void close();
}
package com.hspedu.jdbc.myjdbc;
/**
* 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 的连贯");
}
}
package com.hspedu.jdbc.myjdbc;
/**
* @author 韩顺平
* @version 1.0
* 模仿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的连贯");
}
}
package com.hspedu.jdbc.myjdbc;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
import java.util.Scanner;
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提供一套用于数据库操作的接口APl, Java程序员只须要面向这套接口编程即可。不同的数据库厂商,须要针对这套接口,提供不同实现。
JDBC API是一系列的接口,它对立和标准了应用程序与数据库的连贯、执行SQL语句,并到失去返回后果等各类操作,相干类和接口在java.sql与javax.sql包中
JDBC 疾速入门
JDBC 程序编写步骤
- 注册驱动–加载Driver类
- 获取连贯–失去Connection(java程序和数据库之间的连贯)
- 执行增删改查–发送SQL给mysql执行
- 开释资源–敞开相干连贯
JDBC 第一个程序
通过jdbc对表actor 进行增加,删除和批改操作
package com.hspedu.jdbc;
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 这是第一个Jdbc 程序,实现简略的操作
*/
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/hsp_db02";
//将 用户名和明码放入到Properties 对象
Properties properties = new Properties();
//阐明 user 和 password 是规定好,前面的值依据理论状况写
properties.setProperty("user", "root");// 用户
properties.setProperty("password", "hsp"); //明码
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
//形式1
@Test
public void connect01() throws SQLException {
Driver driver = new Driver(); //创立driver对象
String url = "jdbc:mysql://localhost:3306/hsp_db02";
//将 用户名和明码放入到Properties 对象
Properties properties = new Properties();
//阐明 user 和 password 是规定好,前面的值依据理论状况写
properties.setProperty("user", "root");// 用户
properties.setProperty("password", "hsp"); //明码
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
形式2
//形式2
@Test
public void connect02() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
//应用反射加载Driver类 , 动静加载,更加的灵便,缩小依赖性(把forName后的信息放在配置文件上更加不便)
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)aClass.newInstance();
String url = "jdbc:mysql://localhost:3306/hsp_db02";
//将 用户名和明码放入到Properties 对象
Properties properties = new Properties();
//阐明 user 和 password 是规定好,前面的值依据理论状况写
properties.setProperty("user", "root");// 用户
properties.setProperty("password", "hsp"); //明码
Connection connect = driver.connect(url, properties);
System.out.println("形式2=" + connect);
}
形式3
应用DriverManager 代替 driver 进行对立治理
//形式3 应用DriverManager 代替 driver 进行对立治理
@Test
public void connect03() throws IllegalAccessException, InstantiationException, ClassNotFoundException, SQLException {
//应用反射加载Driver
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//创立url 和 user 和 password
String url = "jdbc:mysql://localhost:3306/hsp_db02";
String user = "root";
String password = "hsp";
DriverManager.registerDriver(driver);//注册Driver驱动
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第三种形式=" + connection);
}
形式4
//形式4: 应用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.jdbc.Driver");
//创立url 和 user 和 password
String url = "jdbc:mysql://localhost:3306/hsp_db02";
String user = "root";
String password = "hsp";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第4种形式~ " + connection);
}
- mysqL驱动5.1.6 能够无需 CLass . forName(“com.mysql.jdbc.Driver”);
- 从jdk1.5当前应用了jdbc4,不再须要显示调用class.forName()注册驱动而是主动调用驱动jar包下
META-INF\servicesViava.sql.Driver
文本中的类名称去注册 - 倡议还是写上 CLass . forName(“com.mysql.jdbc.Driver”),更加明确
形式5
//形式5 , 在形式4的根底上改良,减少配置文件,让连贯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);
}
ResultSet[后果集]
根本介绍
- 示意数据库后果集的数据表,通常通过执行查询数据库的语句生成
- ResultSet对象放弃一个光标指向其以后的数据行。最后,光标位于第一行之前
- next办法将光标挪动到下一行,并且因为在ResultSet对象中没有更多行时返回false,因而能够在while循环中应用循环来遍历后果集
利用实例
package com.hspedu.jdbc.resultset_;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* 演示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();
}
}
Statement
根本介绍
- Statement对象用于执行动态SQL语句并返回其生成的后果的对象
-
在连贯建设后,须要对数据库进行拜访,执行命名或是SQL语句,能够通过
- Statement[存在SQL注入]
- PreparedStatement[预处理]
- CallableStatement[存储过程]
-
Statement对象执行SQL语句,存在SQL注入危险。
- SQL注入是利用某些零碎没有对用户输出的数据进行充沛的查看,而在用户输出数据中注入非法的SQL语句段或命令,歹意攻打数据库。
- 要防备SQL注入,只有用 PreparedStatement(从Statement扩大而来)取代Statement就能够了。
package com.hspedu.jdbc.statement_;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;
/**
* 演示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();
}
}
PreparedStatement
根本介绍
String sql ="SELECT COUNT(*) FROM admin WHERE username =? AND PASSWORD=?";
- PreparedStatement 执行的SQL语句中的参数用问号(?)来示意,调用
PreparedStatement对象的setXxx()办法来设置这些参数. setXxx()办法有两个参数,第一个参数是要设置的SQL语句中的参数的索引(从1开始),第二个是设置的SQL语句中的参数的值 - 调用executeQuery0),返回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;
/**
* 演示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(sql);
if (resultSet.next()) { //如果查问到一条记录,则阐明该治理存在
System.out.println("祝贺, 登录胜利");
} else {
System.out.println("对不起,登录失败");
}
//敞开连贯
resultSet.close();
preparedStatement.close();
connection.close();
}
}
操作DML语句
package com.hspedu.jdbc.preparedstatement_;
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应用 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();
}
}
JDBC 的相干 API 小结
封装JDBCUtils
阐明
在jdbc操作中,获取连贯和开释资源是常常应用到,能够将其封装DBC连贯的工真类JDBCUtils。
代码实现
package com.hspedu.jdbc.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* 这是一个工具类,实现 mysql的连贯和敞开资源
*/
public class JDBCUtils {
//定义相干的属性(4个), 因为只须要一份,因而,咱们做成static
private static String user; //用户名
private static String password; //明码
private static String url; //url
private static String driver; //驱动名
//在static代码块去初始化
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//读取相干的属性值
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
driver = properties.getProperty("driver");
} 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);
}
}
}
测试
package com.hspedu.jdbc.utils;
import org.junit.jupiter.api.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);
}
}
}
事务
根本介绍
- 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;
/**
* 演示jdbc 中如何应用事务
*/
public class Transaction_ {
//没有应用事务.
@Test
public void noTransaction() {
//操作转账的业务
//1. 失去连贯
Connection connection = null;
//2. 组织一个sql
String sql = "update account set balance = balance - 100 where id = 1";
String sql2 = "update account set balance = balance + 100 where id = 2";
PreparedStatement preparedStatement = null;
//3. 创立PreparedStatement 对象
try {
connection = JDBCUtils.getConnection(); // 在默认状况下,connection是默认主动提交
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate(); // 执行第1条sql
int i = 1 / 0; //抛出异样
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate(); // 执行第3条sql
} catch (SQLException e) {
e.printStackTrace();
} finally {
//敞开资源
JDBCUtils.close(null, preparedStatement, connection);
}
}
//事务来解决
@Test
public void useTransaction() {
//操作转账的业务
//1. 失去连贯
Connection connection = null;
//2. 组织一个sql
String sql = "update account set balance = balance - 100 where id = 1";
String sql2 = "update account set balance = balance + 100 where id = 2";
PreparedStatement preparedStatement = null;
//3. 创立PreparedStatement 对象
try {
connection = JDBCUtils.getConnection(); // 在默认状况下,connection是默认主动提交
//将 connection 设置为不主动提交
connection.setAutoCommit(false); // 相当于开启了事务
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate(); // 执行第1条sql
int i = 1 / 0; //抛出异样
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate(); // 执行第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一起搭配应用,能够既缩小编译次数,又减小运行次数,效率大大提高。
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);
}
//应用批量形式增加数据
@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);
}
}
数据库连接池
5k 次连贯数据库问题
package com.hspedu.jdbc.datasource;
import com.hspedu.jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
public class ConQuestion {
//代码 连贯mysql 5000次
@Test
public void testCon() {
//看看连贯-敞开 connection 会耗用多久
long start = System.currentTimeMillis();
System.out.println("开始连贯.....");
for (int i = 0; i < 5000; i++) {
//应用传统的jdbc形式,失去连贯
Connection connection = JDBCUtils.getConnection();
//做一些工作,比方失去PreparedStatement ,发送sql
//..........
//敞开
JDBCUtils.close(null, null, connection);
}
long end = System.currentTimeMillis();
System.out.println("传统形式5000次 耗时=" + (end - start));//传统形式5000次 耗时=7099
}
}
传统获取Connection 问题剖析
- 传统的JDBC数据库连贯应用 DriverManager 来获取,每次向数据库建设连贯的时候都要将 Connection 加载到内存中,再验证IP地址,用户名和明码(0.05s~1s工夫)。须要数据库连贯的时候,就向数据库要求一个,频繁的进行数据库连贯操作将占用很多的系统资源,容易造成服务器解体。
- 每一次数据库连贯,应用完后都得断开,如果程序出现异常而未能敞开,将导致数据库内存透露,最终将导致重启数据库。
- 传统获取连贯的形式,不能管制创立的连贯数量,如连贯过多,也可能导致内存透露,MySQL解体。
- 解决传统开发中的数据库连贯问题,能够采纳数据库连接池技术
(connection pool)。
数据库连接池品种
- JDBC 的数据库连接池应用javax.sqI.DataSource来示意,DataSource 只是一个接口,该接口通常由第三方提供实现[提供.jar]
- C3P0数据库连接池,速度绝对较慢,稳定性不错(hibernate, spring)
- DBCP数据库连接池,速度绝对c3p0较快,但不稳固
- Proxool数据库连接池,有监控连接池状态的性能,稳定性较c3p0差一点
- BoneCP数据库连接池,速度快
- Druid(德鲁伊)是阿里提供的数据库连接池,集DBCP、C3P0、Proxool长处于一身的数据库连接池
C3P0 利用实例
两种连贯形式:
package com.hspedu.jdbc.datasource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
* 演示c3p0的应用
*/
public class C3P0_ {
//形式1: 相干参数,在程序中指定user, url , password等
@Test
public void testC3P0_01() throws Exception {
//1. 创立一个数据源对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//2. 通过配置文件mysql.properties 获取相干连贯的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//读取相干的属性值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//给数据源 comboPooledDataSource 设置相干的参数
//留神:连贯治理是由 comboPooledDataSource 来治理
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(user);
comboPooledDataSource.setPassword(password);
//设置初始化连接数
comboPooledDataSource.setInitialPoolSize(10);
//最大连接数
comboPooledDataSource.setMaxPoolSize(50);
//测试连接池的效率, 测试对mysql 5000次操作
long start = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
Connection connection = comboPooledDataSource.getConnection(); //这个办法就是从 DataSource 接口实现的
//System.out.println("连贯OK");
connection.close();
}
long end = System.currentTimeMillis();
//c3p0 5000连贯mysql 耗时=391
System.out.println("c3p0 5000连贯mysql 耗时=" + (end - start));
}
//第二种形式 应用配置文件模板来实现
//1. 将c3p0 提供的 c3p0.config.xml 拷贝到 src目录下(配置文件名字不能乱写,要依照规定)
//2. 该文件指定了连贯数据库和连接池的相干参数
@Test
public void testC3P0_02() throws SQLException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("hsp_edu");
//测试5000次连贯mysql
long start = System.currentTimeMillis();
System.out.println("开始执行....");
for (int i = 0; i < 500000; i++) {
Connection connection = comboPooledDataSource.getConnection();
//System.out.println("连贯OK~");
connection.close();
}
long end = System.currentTimeMillis();
//c3p0的第二种形式 耗时=413
System.out.println("c3p0的第二种形式(500000) 耗时=" + (end - start));//1917
}
}
<c3p0-config>
<!-- 数据源名称代表连接池 -->
<named-config name="hsp_edu">
<!-- 驱动类 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<!-- url-->
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/hsp_db02</property>
<!-- 用户名 -->
<property name="user">root</property>
<!-- 明码 -->
<property name="password">hsp</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>
Druid(德鲁伊)利用实例
#key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/hsp_db02?rewriteBatchedStatements=true
username=root
password=hsp
#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
package com.hspedu.jdbc.datasource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.jupiter.api.Test;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;
/**
* 测试druid的应用
*/
public class Druid_ {
@Test
public void testDruid() throws Exception {
//1. 退出 Druid jar包
//2. 退出 配置文件 druid.properties , 将该文件拷贝我的项目的src目录
//3. 创立Properties对象, 读取配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("src\\druid.properties"));
//4. 创立一个指定参数的数据库连接池, Druid连接池
DataSource dataSource =
DruidDataSourceFactory.createDataSource(properties);
long start = System.currentTimeMillis();
for (int i = 0; i < 500000; i++) {
Connection connection = dataSource.getConnection();
System.out.println(connection.getClass());
//System.out.println("连贯胜利!");
connection.close();
}
long end = System.currentTimeMillis();
//druid连接池 操作5000 耗时=412
System.out.println("druid连接池 操作500000 耗时=" + (end - start));//539
}
}
将JDBCUtils 工具类改成Druid(德鲁伊)实现
通过德鲁伊数据库连接池获取连贯对象
package com.hspedu.jdbc.datasource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 基于druid数据库连接池的工具类
*/
public class JDBCUtilsByDruid {
private static DataSource ds;
//在动态代码块实现 ds初始化
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src\\druid.properties"));
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//编写getConnection办法
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//敞开连贯, 老师再次强调: 在数据库连接池技术中,close 不是真的断掉连贯
//而是把应用的Connection对象放回连接池
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
// 特地留神:这里close办法与元生的close办法不一样,这里仅是放回连接池。
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
package com.hspedu.jdbc.datasource;
import org.junit.jupiter.api.Test;
import java.sql.*;
import java.util.ArrayList;
@SuppressWarnings({"all"})
public class JDBCUtilsByDruid_USE {
@Test
public void testSelect() {
System.out.println("应用 druid形式实现");
//1. 失去连贯
Connection connection = null;
//2. 组织一个sql
String sql = "select * from 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);
}
}
}
Apache—DBUtils
先剖析一个问题
- 敞开connection后,resultSet后果集无奈应用
- resultSet不利于数据的治理
- 示意图
这种java类叫做JavaBean,PoJo或者Domain。
自定义办法解决
package com.hspedu.jdbc.datasource;
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 + '\'' +
'}';
}
}
//应用老师的土办法来解决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;
}
根本介绍
commons-dbutils是 Apache组织提供的一个开源JDBC工具类库,它是对JDBC的封装,应用dbutils能极大简化jdbc编码的工作量。
- DbUtils类:
- QueryRunner类:该类封装了SQL的执行,是线程平安的。能够实现增、删、改、查、批处理。
- 应用QueryRunner类实现查问。
-
ResultSetHandler接口:该接口用于解决java.sql.ResultSet,将数据按要求转换为另一种模式。
- 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的crud
package com.hspedu.jdbc.datasource;
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.jupiter.api.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,所以只须要传入connection就能够。
/**
* 剖析 queryRunner.query办法:
* public <T> T query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {
* PreparedStatement stmt = null;//定义PreparedStatement
* ResultSet rs = null;//接管返回的 ResultSet
* Object result = null;//返回ArrayList
*
* try {
* stmt = this.prepareStatement(conn, sql);//创立PreparedStatement
* this.fillStatement(stmt, params);//对sql 进行 ? 赋值
* rs = this.wrap(stmt.executeQuery());//执行sql,返回resultset
* result = rsh.handle(rs);//返回的resultset --> arrayList[result] [应用到反射,对传入class对象解决]
* } catch (SQLException var33) {
* this.rethrow(var33, sql, params);
* } finally {
* try {
* this.close(rs);//敞开resultset
* } finally {
* this.close((Statement)stmt);//敞开preparedstatement对象
* }
* }
*
* return result;
* }
*/
List<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);
}
}
表 和 JavaBean 的类型映射关系
DAO 和增删改查通用办法-BasicDao
先剖析一个问题
apache-dbutils+ Druid简化了JDBC开发,但还有有余:
- SQL语句是固定,不能通过参数传入,通用性不好,须要进行改良,更不便执行增删改查
- 对于select 操作,如果有返回值,返回类型不能固定,须要应用泛型
- 未来的表很多,业务需要简单,不可能只靠一个Java类实现
- 引出=》 BasicDAO画出示意图,看看在理论开发中,应该如何解决
根本阐明
- DAO : data access object数据拜访对象
- 这样的通用类,称为 BasicDao,是专门和数据库交互的,即实现对数据库(表)的crud操作。
- 在BaiscDao的根底上,实现一张表对应一个Dao,更好的实现性能,比方 Customer表-Customer.java类(javabean)-CustomerDao.java
BasicDAO 利用实例
实现一个简略设计com.hspedu.dao_
com.hspedu.dao _.utils
//工具类com.hspedu.dao_.domain
// javabeancom.hspedu.dao_.dao
//寄存XxxDAO和BasicDAO_com.hspedu.dao_.test
//写测试类
com/hspedu/dao_/domain/Actor.java
package com.hspedu.dao_.domain;
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 + '\'' +
'}';
}
}
com/hspedu/dao_/utils/JDBCUtilsByDruid.java
package com.hspedu.dao_.domain;
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 + '\'' +
'}';
}
}
com/hspedu/dao_/dao/BasicDAO.java
package com.hspedu.dao_.dao;
import com.hspedu.dao_.utils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
/**
* 开发BasicDAO , 是其余DAO的父类
*/
public class BasicDAO<T> { //泛型指定具体类型
private QueryRunner qr = new QueryRunner();
//开发通用的dml办法, 针对任意的表
public int update(String sql, Object... parameters) {
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
int update = qr.update(connection, sql, parameters);
return update;
} catch (SQLException e) {
throw new RuntimeException(e); //将编译异样->运行异样 ,抛出
} finally {
JDBCUtilsByDruid.close(null, null, connection);
}
}
//返回多个对象(即查问的后果是多行), 针对任意表
/**
*
* @param sql sql 语句,能够有 ?
* @param clazz 传入一个类的Class对象 比方 Actor.class
* @param parameters 传入 ? 的具体的值,能够是多个
* @return 依据Actor.class 返回对应的 ArrayList 汇合
*/
public List<T> queryMulti(String sql, Class<T> clazz, Object... parameters) {
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters);
} catch (SQLException e) {
throw new RuntimeException(e); //将编译异样->运行异样 ,抛出
} finally {
JDBCUtilsByDruid.close(null, null, connection);
}
}
//查问单行后果 的通用办法
public T querySingle(String sql, Class<T> clazz, Object... parameters) {
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new BeanHandler<T>(clazz), parameters);
} catch (SQLException e) {
throw new RuntimeException(e); //将编译异样->运行异样 ,抛出
} finally {
JDBCUtilsByDruid.close(null, null, connection);
}
}
//查问单行单列的办法,即返回单值的办法
public Object queryScalar(String sql, Object... parameters) {
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new ScalarHandler(), parameters);
} catch (SQLException e) {
throw new RuntimeException(e); //将编译异样->运行异样 ,抛出
} finally {
JDBCUtilsByDruid.close(null, null, connection);
}
}
}
com/hspedu/dao_/dao/ActorDAO.java
package com.hspedu.dao_.dao;
import com.hspedu.dao_.domain.Actor;
public class ActorDAO extends BasicDAO<Actor> {
//1. 就有 BasicDAO 的办法
//2. 依据业务需要,能够编写特有的办法.
}
com/hspedu/dao_/test/TestDAO.java
package com.hspedu.dao_.test;
import com.hspedu.dao_.dao.ActorDAO;
import com.hspedu.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 ? "执行胜利" : "执行没有影响表");
}
}
发表回复