一、JDBC概述
1 基本介绍
2 简单模拟
package com.hspedu.jdbc.myjdbc;/*** @author 林然* @version 1.0* 我们规定的 jdbc 接口(方法)*/
public interface JdbcInterface {//连接public Object getConnection() ;//crudpublic void crud();//关闭连接public void close();
}
package com.hspedu.jdbc.myjdbc;/*** @author 林然* @version 1.0* mysql 数据库实现了 jdbc 接口 [模拟] 【mysql 厂商开发】*/
public class MysqlJdbcImpl implements JdbcInterface{@Overridepublic Object getConnection() {System.out.println("得到 mysql 的连接");return null;}@Overridepublic void crud() {System.out.println("完成 mysql 增删改查");}@Overridepublic void close() {System.out.println("关闭 mysql 的连接");}
}
package com.hspedu.jdbc.myjdbc;/*** @author 林然* @version 1.0*/
public class OracleJdbcImpl implements JdbcInterface{@Overridepublic Object getConnection() {System.out.println("得到 oracle 的连接 升级");return null;}@Overridepublic void crud() {System.out.println("完成 对 oracle 的增删改查");}@Overridepublic void close() {System.out.println("关闭 oracle 的连接");}
}
package com.hspedu.jdbc.myjdbc;/*** @author 林然* @version 1.0*/
public class TestJDBC {public static void main(String[] args) {//完成对 mysql 的操作JdbcInterface jdbcInterface = new MysqlJdbcImpl();jdbcInterface.getConnection(); //通过接口来调用实现类[动态绑定]jdbcInterface.crud();jdbcInterface.close();//完成对 oracle 的操作System.out.println("==============================");jdbcInterface = new OracleJdbcImpl();jdbcInterface.getConnection(); //通过接口来调用实现类[动态绑定]jdbcInterface.crud();jdbcInterface.close();}
}
3 JDBC 带来的好处
4 JDBC API
二、JDBC快速入门
1 JDBC 程序编写步骤
2 JDBC 第一个程序
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;/*** @author 林然* @version 1.0* 这是第一个 Jdbc 程序,完成简单的操作*/
public class Jdbc01 {public static void main(String[] args) throws SQLException {//前置工作: 在项目下创建一个文件夹比如 libs// 将 mysql.jar 拷贝到该目录下,点击 add to project ..加入到项目中//1. 注册驱动Driver driver = new Driver();//2. 得到连接// 老师解读//(1) jdbc:mysql:// 规定好表示协议,通过 jdbc 的方式连接 mysql//(2) localhost 主机,可以是 ip 地址//(3) 3306 表示 mysql 监听的端口//(4) hsp_db02 连接到 mysql dbms 的哪个数据库//(5) mysql 的连接本质就是前面学过的 socket 连接String url ="jdbc:mysql://localhost:3306/hsp_db02";//将 用户名和密码放入到 Properties 对象Properties properties = new Properties();//说明 user 和 password 是规定好,后面的值根据实际情况写properties.setProperty("user", "root");// 用户properties.setProperty("password", "123456"); //密码Connection connect = driver.connect(url, properties);//3. 执行 sqlString sql = "insert into actor values(null, '刘德华', '男', '1970-11-11', '110')";//statement 用于执行静态 SQL 语句并返回其生成的结果的对象Statement statement = connect.createStatement();int rows = statement.executeUpdate(sql); // 如果是 dml 语句,返回的就是影响行数System.out.println(rows > 0 ? "成功" : "失败");
//4. 关闭连接资源statement.close();connect.close();}
}
三、JDBC API
1 获取数据库连接 5 种方式
1.1 方式 1
1.2 方式 2
1.3 方式 3
1.4 方式 4
1.5 方式 5
1.6 课堂练习
package com.hspedu.jdbc;import com.mysql.jdbc.Driver;
import org.junit.Test;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.sql.Statement;
import java.util.Properties;/*** @author 林然* @version 1.0* 分析 java 连接 mysql 的 5 中方式*/
public class JdbcConn {//方式 1@Testpublic 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", "123456"); //密码Connection connect = driver.connect(url, properties);System.out.println(connect);}//方式 2@Testpublic void connect02() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {//使用反射加载 Driver 类 , 动态加载,更加的灵活,减少依赖性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", "123456"); //密码Connection connect = driver.connect(url, properties);System.out.println(connect);}@Testpublic void connect05() throws IOException, ClassNotFoundException, SQLException, IllegalAccessException, InstantiationException {//通过 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<?> aClass = Class.forName(driver);//建议写上Driver driver1=(Driver)aClass.newInstance();DriverManager.registerDriver(driver1);Connection connection = DriverManager.getConnection(url, user, password);Statement statement=connection.createStatement();String sql1="create table news (id int primary key,`name` varchar(12))";statement.executeUpdate(sql1);String insert_sql="insert into news values(1,'1'),(2,'2'),(3,'3'),(4,'4'),(5,'5')";statement.executeUpdate(insert_sql);statement.close();connection.close();}
}
2 ResultSet[结果集]
2.1 基本介绍
2.2 应用实例
package com.hspedu.jdbc.resultset_;import com.mysql.jdbc.Driver;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;/*** @author 林然* @version 1.0* 演示 select 语句返回 ResultSet ,并取出结果*/
public class ResultSet_ {public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {Properties properties=new Properties();properties.load(new FileInputStream("src\\mysql.properties"));//通过 Properties 对象获取配置文件的信息String user = properties.getProperty("user");String password =properties.getProperty("password");String driver =properties.getProperty("driver");String url= properties.getProperty("url");//1. 注册驱动Class<?> aClass = Class.forName(driver);Driver driver1 =(Driver)aClass.newInstance();DriverManager.registerDriver(driver1);//2. 得到连接Connection conn =DriverManager.getConnection(url,user,password);//3. 得到 StatementStatement statement =conn.createStatement();String sql ="select id,name,sex,borndate from actor";//执行给定的 SQL 语句,该语句返回单个 ResultSet 对象ResultSet resultSet= statement.executeQuery(sql);//5. 使用 while 取出数据while (resultSet.next()){// 让光标向后移动,如果没有更多行,则返回 falseint id= resultSet.getInt("id");String name=resultSet.getString("name");String sex=resultSet.getString("sex");Date date =resultSet.getDate("borndate");System.out.println(id + "\t" + name + "\t" + sex + "\t" + date);}
//关闭连接resultSet.close();statement.close();conn.close();}
}
3 Statement
3.1 基本介绍
3.2 演示的sql语句
-- 演示 sql 注入
-- 创建一张表
CREATE TABLE admin ( -- 管理员表
NAME VARCHAR(32) NOT NULL UNIQUE, pwd VARCHAR(32) NOT NULL DEFAULT '') CHARACTER SET utf8; -- 添加数据
INSERT INTO admin VALUES('tom', '123');
-- 查找某个管理是否存在SELECT *
FROM admin
WHERE NAME = 'tom' AND pwd = '123';-- SQL
-- 输入用户名 为 1'or
-- 输入万能密码 为 or '1'= '1
SELECT *
FROM admin
WHERE NAME = '1' OR' AND pwd = 'OR '1'= '1' SELECT * FROM admin
3.3 应用实例
package com.hspedu.jdbc.statement_;import com.mysql.jdbc.Driver;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;/*** @author 林然* @version 1.0* 演示 statement 的注入问题*/
public class Statement_ {public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {Scanner scanner = new Scanner(System.in);//让用户输入管理员名和密码System.out.print("请输入管理员的名字: "); //next(): 当接收到 空格或者 '就是表示结束String admin_name = scanner.nextLine(); // 老师说明,如果希望看到 SQL 注入,这里需要用 nextLineSystem.out.print("请输入管理员的密码: ");String admin_pwd = scanner.nextLine();Properties properties=new Properties();properties.load(new FileInputStream("src\\mysql.properties"));//通过 Properties 对象获取配置文件的信息String user = properties.getProperty("user");String password =properties.getProperty("password");String driver =properties.getProperty("driver");String url= properties.getProperty("url");//1. 注册驱动Class<?> aClass = Class.forName(driver);Driver driver1 =(Driver)aClass.newInstance();DriverManager.registerDriver(driver1);//2. 得到连接Connection conn =DriverManager.getConnection(url,user,password);//3. 得到 StatementStatement statement =conn.createStatement();//4. 组织 SqLString 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();conn.close();}
}
4 PreparedStatement
4.1 基本介绍
4.2 预处理好处
4.3 应用案例
package com.hspedu.jdbc.preparedstatement_;import com.mysql.jdbc.Driver;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;/*** @author 林然* @version 1.0* 演示 PreparedStatement 使用*/
public class PreparedStatement_ {public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {Scanner scanner = new Scanner(System.in);//让用户输入管理员名和密码System.out.print("请输入管理员的名字: "); //next(): 当接收到 空格或者 '就是表示结束String admin_name = scanner.nextLine(); // 老师说明,如果希望看到 SQL 注入,这里需要用 nextLineSystem.out.print("请输入管理员的密码: ");String admin_pwd = scanner.nextLine();Properties properties=new Properties();properties.load(new FileInputStream("src\\mysql.properties"));//通过 Properties 对象获取配置文件的信息String user = properties.getProperty("user");String password =properties.getProperty("password");String driver =properties.getProperty("driver");String url= properties.getProperty("url");//1. 注册驱动Class<?> aClass = Class.forName(driver);Driver driver1 =(Driver)aClass.newInstance();DriverManager.registerDriver(driver1);//2. 得到连接Connection conn =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 =conn.prepareStatement(sql);//3.3 给 ? 赋值preparedStatement.setString(1,admin_name);preparedStatement.setString(2,admin_pwd);//4. 执行 select 语句使用 executeQuery// 如果执行的是 dml(update, insert ,delete) executeUpdate()// 这里执行 executeQuery ,不要在写 sqlResultSet resultSet =preparedStatement.executeQuery();if(resultSet.next()){System.out.println("恭喜, 登录成功");}else {System.out.println("对不起,登录失败");}String sql1="insert into admin values(?,?)";PreparedStatement preparedStatement1 =conn.prepareStatement(sql1);preparedStatement1.setString(1,"linran");preparedStatement1.setString(2,"123456");//执行 dml 语句使用 executeUpdateint rows=preparedStatement1.executeUpdate();System.out.println(rows > 0 ? "执行成功" : "执行失败");//关闭连接preparedStatement1.close();resultSet.close();preparedStatement.close();conn.close();}
}
5 JDBC 的相关 API 小结
四、JDBC Utils
1 说明
2 jDBC Utils代码实现
package com.hspedu.jdbc.utils;import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;/*** @author 林然* @version 1.0* 这是一个工具类,完成 mysql 的连接和关闭资源*/
public class JDBCUtils {//定义相关的属性(4 个), 因为只需要一份,因此,我们做出 staticprivate static String user; //用户名private static String password; //密码private static String url; //urlprivate 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);}}//连接数据库, 返回 Connectionpublic static Connection getConnection() {try {Class<?> aClass = Class.forName(driver);Driver driver1 =(Driver)aClass.newInstance();DriverManager.registerDriver(driver1);return DriverManager.getConnection(url, user, password);} catch (SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {//1. 将编译异常转成 运行异常//2. 调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便.throw new RuntimeException(e);}}//关闭相关资源/*1. ResultSet 结果集2. Statement 或者 PreparedStatement3. Connection4. 如果需要关闭资源,就传入对象,否则传入 null*/public static void close(ResultSet set, Statement statement, Connection connection) {
//判断是否为 nulltry {if (set != null) {set.close();}if (statement != null) {statement.close();}if (connection != null) {connection.close();}} catch (SQLException e) {
//将编译异常转成运行异常抛出throw new RuntimeException(e);}}}
3 使用实例
package com.hspedu.jdbc.utils;import org.junit.Test;import java.sql.*;/*** @author 林然* @version 1.0* 该类演示如何使用 JDBCUtils 工具类,完成 dml 和 select*/
public class JDBCUtils_Use {@Testpublic void testSelect() {//1. 得到连接Connection connection=JDBCUtils.getConnection();//2. 组织一个 sqlString sql="select * from actor where id=?";PreparedStatement preparedStatement=null;ResultSet set = null;try {preparedStatement=connection.prepareStatement(sql);preparedStatement.setInt(1,2);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 throwables) {throwables.printStackTrace();} finally {//关闭资源JDBCUtils.close(set, preparedStatement, connection);}}@Testpublic void testDML() {//insert , update, delete//得到连接Connection connection = (Connection) JDBCUtils.getConnection();//2. 组织一个 sqlString sql = "update actor set name = ? where id = ?";// 测试 delete 和 insert ,自己玩. PreparedStatement preparedStatement = null;//3. 创建 PreparedStatement 对象PreparedStatement preparedStatement=null;try {preparedStatement = (PreparedStatement) connection.prepareStatement(sql);preparedStatement.setString(1,"周星驰");preparedStatement.setInt(2,2);preparedStatement.executeUpdate();} catch (SQLException throwables) {throwables.printStackTrace();} finally {//关闭JDBCUtils.close(null,preparedStatement,connection);}}
}
五、事务
1 基本介绍
2 应用实例
- 模拟经典的转账业务
3 使用事务解决上述问题-模拟经典的转账业务
package com.hspedu.jdbc.transaction_;import com.hspedu.jdbc.utils.JDBCUtils;
import org.junit.Test;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;/*** @author 林然* @version 1.0*/
public class Transaction_ {//没有使用事务.@Testpublic void noTransaction() {//操作转账的业务//1. 得到连接Connection connection = null;//2. 组织一个 sqlString sql = "update account set banlance = banlance - 100 where id = 1";String sql2 = "update account set banlance = banlance + 100 where id = 2";PreparedStatement preparedStatement = null;//3. 创建 PreparedStatement 对象try {connection = JDBCUtils.getConnection(); // 在默认情况下,connection 是默认自动提交preparedStatement = connection.prepareStatement(sql);preparedStatement.executeUpdate(); // 执行第 1 条 sqlint i = 1 / 0; //抛出异常preparedStatement = connection.prepareStatement(sql2);preparedStatement.executeUpdate(); // 执行第 3 条 sql} catch (SQLException e) {e.printStackTrace();} finally {//关闭资源JDBCUtils.close(null, preparedStatement, connection);}}//事务来解决@Testpublic void useTransaction() {//操作转账的业务//1. 得到连接Connection connection = null;//2. 组织一个 sqlString sql = "update account set banlance = banlance - 100 where id = 1";String sql2 = "update account set banlance = banlance + 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 条 sqlint i = 1 / 0; //抛出异常preparedStatement = connection.prepareStatement(sql2);preparedStatement.executeUpdate(); // 执行第 3 条 sql//这里提交事务connection.commit();} catch (SQLException e) {e.printStackTrace();//这里我们可以进行回滚,即撤销执行的 SQL
//默认回滚到事务开始的状态. System.out.println("执行发生了异常,撤销执行的 sql");try {connection.rollback();} catch (SQLException throwables) {throwables.printStackTrace();}e.printStackTrace();} finally {//关闭资源JDBCUtils.close(null, preparedStatement, connection);}}}
六、批处理
1 基本介绍
2 应用实例
package com.hspedu.jdbc.batch_;import com.hspedu.jdbc.utils.JDBCUtils;
import org.junit.Test;import java.sql.Connection;
import java.sql.PreparedStatement;/*** @author 林然* @version 1.0* 演示 java 的批处理*/
public class Batch_ {//传统方法,添加 5000 条数据到 admin2@Testpublic 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);}//使用批量方式添加数据@Testpublic 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语句加入p处理preparedStatement.addBatch();//当有 1000 条记录时,在批量执行if((i + 1) % 1000 == 0) {//满 1000 条 sqlpreparedStatement.executeBatch();//清空一把preparedStatement.clearBatch();}}long end = System.currentTimeMillis();System.out.println("批量方式 耗时=" + (end - start));//批量方式 耗时=108//关闭连接JDBCUtils.close(null, preparedStatement, connection);}
}
七、连接池
1 5k 次连接数据库问题
package com.hspedu.jdbc.datasource;import com.hspedu.jdbc.utils.JDBCUtils;
import org.junit.Test;import java.sql.Connection;/*** @author 林然* @version 1.0*/
public class ConQuestion {//代码 连接 mysql 5000 次@Testpublic 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}
}
2 传统获取 Connection 问题分析
3 数据库连接池种类
4 C3P0 应用实例
package com.hspedu.jdbc.datasource;import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;/*** @author 林然* @version 1.0* 演示 c3p0 的使用*/
public class C3P0_ {//方式 1: 相关参数,在程序中指定 user, url , password 等@Testpublic void testC3P0_01() throws IOException, PropertyVetoException, SQLException {//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 耗时=391System.out.println("c3p0 5000 连接 mysql 耗时=" + (end - start));}//第二种方式 使用配置文件模板来完成//1. 将 c3p0 提供的 c3p0.config.xml 拷贝到 src 目录下//2. 该文件指定了连接数据库和连接池的相关参数@Testpublic void testC3P0_02() throws SQLException {ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("lin_ran");//测试 5000 次连接 mysqllong start = System.currentTimeMillis();System.out.println("开始执行....");for (int i = 0; i < 5000; i++) {Connection connection = comboPooledDataSource.getConnection();//System.out.println("连接 OK~");connection.close();}long end = System.currentTimeMillis();//c3p0 的第二种方式 耗时=413System.out.println("c3p0 的第二种方式(5000) 耗时=" + (end - start));//1917}
}
5 Druid(德鲁伊)应用实例
package com.hspedu.jdbc.datasource;import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;/*** @author 林然* @version 1.0* 测试 druid 的使用*/
public class Druid_ {@Testpublic 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 < 5000; i++) {Connection connection = dataSource.getConnection();System.out.println(connection.getClass());//System.out.println("连接成功!");connection.close();}long end = System.currentTimeMillis();//druid 连接池 操作 5000 耗时=412System.out.println("druid 连接池 操作 500000 耗时=" + (end - start));//539}}
6 将 JDBCUtils 工具类改成 Druid(德鲁伊)实现
package com.hspedu.jdbc.datasource;import org.junit.Test;import java.sql.*;/*** @author 林然* @version 1.0*/
public class JDBCUtilsByDruid_USE {@Testpublic void testSelect() throws SQLException {System.out.println("使用 druid 方式完成");//1. 得到连接Connection connection =JDBCUtilsByDruid.getConnection();//String sql = "select * from actor where id >= ?";PreparedStatement preparedStatement = null;//3. 创建 PreparedStatement 对象ResultSet set = null;try {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 throwables) {throwables.printStackTrace();} finally {//关闭资源JDBCUtilsByDruid.close(set, preparedStatement, connection);}}
}
package com.hspedu.jdbc.datasource;import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;/*** @author 林然* @version 1.0* 基于 druid 数据库连接池的工具类*/
public class JDBCUtilsByDruid {public 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) throws SQLException {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
1 先分析一个问题
2 用自己的土方法来解决
3 基本介绍
4 应用实例
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.Test;import java.sql.*;
import java.util.List;/*** @author 林然* @version 1.0*/
public class DBUtils_USE {//使用apache-DBUtils 工具类 +druid完成对表的crud的操作@Testpublic void testQueryMany() throws SQLException {//返回结果是多行的情况//1 得到;连接 (druid)Connection connection =JDBCUtilsByDruid.getConnection();//2 使用DBUtils的类和接口,先引入DBUtils的jar文件 加入到本project中//3 创建QueryRunnerQueryRunner queryRunner=new QueryRunner();//4 就可以执行相关的方法,返回ArraryList结果集合String sql="select * 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 关闭, 关闭 PreparedStatmentList<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);}@Testpublic void testQuerySingle() throws SQLException {Connection connection =JDBCUtilsByDruid.getConnection();//2 使用DBUtils的类和接口,先引入DBUtils的jar文件 加入到本project中//3 创建QueryRunnerQueryRunner queryRunner=new QueryRunner();//4 就可以执行相关的方法,返回单个结果集合String sql="select * from actor where id =?";// 因为我们返回的单行记录<--->单个对象 , 使用的 Hander 是 BeanHandlerActor actor=queryRunner.query(connection,sql,new BeanHandler<>(Actor.class),1);System.out.print(actor);JDBCUtilsByDruid.close(null,null,connection);}@Testpublic void testScalar() throws SQLException {//1. 得到 连接 (druid)Connection connection = JDBCUtilsByDruid.getConnection();//2. 使用 DBUtils 类和接口 , 先引入 DBUtils 相关的 jar , 加入到本 Project//3. 创建 QueryRunnerQueryRunner queryRunner = new QueryRunner();//4. 就可以执行相关的方法,返回单行单列 , 返回的就是 ObjectString sql = "select name from actor where id = ?";//老师解读: 因为返回的是一个对象, 使用的 handler 就是 ScalarHandlerObject obj = queryRunner.query(connection, sql, new ScalarHandler(), 1);System.out.println(obj);// 释放资源JDBCUtilsByDruid.close(null, null, connection);}//演示 apache-dbutils + druid 完成 dml (update, insert ,delete)@Testpublic void testDML() throws SQLException {//1. 得到 连接 (druid)Connection connection = JDBCUtilsByDruid.getConnection();//2. 使用 DBUtils 类和接口 , 先引入 DBUtils 相关的 jar , 加入到本 Project//3. 创建 QueryRunnerQueryRunner queryRunner = new QueryRunner();//这里我们可以组织sql语句,完成update,insert,deletString sql ="update actor set name=? where id =?";//(1) 执行 dml 操作是 queryRunner.update()//(2) 返回的值是受影响的行数 (affected: 受影响)int affectedRow=queryRunner.update(connection,sql,"张三丰",1);System.out.println(affectedRow > 0 ? "执行成功" : "执行没有影响到表");// 释放资源JDBCUtilsByDruid.close(null, null, connection);}
}
5 表和 JavaBean 的类型映射关系
九、DAO增删改查-BasucDao
1 先分析一个问题
2 基本说明
3 BasicDAO 应用实例
【package utils】
package com.hspedu.dao_.utils;import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;/*** @author 林然* @version 1.0* 基于 druid 数据库连接池的工具类*/
public class JDBCUtilsByDruid {public 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) throws SQLException {try {if (resultSet != null) {resultSet.close();}if (statement != null) {statement.close();}if (connection != null) {connection.close();}} catch (SQLException e) {throw new RuntimeException(e);}}
}
【package domain】
package com.hspedu.dao_.domain;import java.util.Date;/*** @author 韩顺平* @version 1.0* 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;}@Overridepublic String toString() {return "\nActor{" +"id=" + id +", name='" + name + '\'' +", sex='" + sex + '\'' +", borndate=" + borndate +", phone='" + phone + '\'' +'}';}
}
【dao】
package com.hspedu.dao_.dao;import com.hspedu.dao_.domain.Actor;/*** @author 林然* @version 1.0*/
public class ActorDAO extends BasicDAO<Actor> {//1. 就有 BasicDAO 的方法
//2. 根据业务需求,可以编写特有的方法.
}
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;/*** @author 林然* @version 1.0* 开发BasicDAO ,是其他DAO的父类*/
public class BasicDAO<T> {//泛型指定具体类型private QueryRunner qr =new QueryRunner();//开发通用的dml方法,针对任意的表public int update(String sql,Object... parameters) throws SQLException {Connection connection=null;try {connection=JDBCUtilsByDruid.getConnection();int row=qr.update(connection,sql,parameters);return row;} catch (SQLException throwables) {throw new RuntimeException(throwables);//将编译异常转换成运行异常}finally {JDBCUtilsByDruid.close(null,null,connection);}}//返回多个对象(也就是查询的结果是多行的),针对任意的表/**** @param sql sql 语句,可以有 ?* @param clazz 传入一个类的 Class 对象 比如 Actor.class* @param parameters 传入 ? 的具体的值,可以是多个* @return 根据 Actor.class 返回对应的 ArrayList 集合*/public List<T> querryMulti(String sql,Class<T> clazz,Object... parameters) throws SQLException {Connection connection=null;try {connection=JDBCUtilsByDruid.getConnection();return qr.query(connection,sql,new BeanListHandler<>(clazz),parameters);} catch (SQLException throwables) {throw new RuntimeException(throwables);} finally {JDBCUtilsByDruid.close(null,null,connection);}}//查询单行结果的通用方法public T querySingle(String sql,Class<T> clazz,Object... parameters) throws SQLException {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) throws SQLException {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);}}
}
【test】
package com.hspedu.dao_.test;import com.hspedu.dao_.dao.ActorDAO;
import com.hspedu.dao_.domain.Actor;
import org.junit.Test;import java.sql.SQLException;
import java.util.List;/*** @author 林然* @version 1.0*/
public class TestDAO {//测试 ActorDAO 对 actor 表 crud 操作@Testpublic void testActorDao() throws SQLException {ActorDAO actorDAO=new ActorDAO();//1 查询List<Actor> actors =actorDAO.querryMulti("select * from actor where id>=?",Actor.class,1);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, deleteint update = actorDAO.update("insert into actor values(null, ?, ?, ?, ?)", "张无忌", "男", "2000-11-11", "999");System.out.println(update > 0 ? "执行成功" : "执行没有影响表");}
}