学习目标:
JDBC
JDBC工具类
SQL注入
一、JDBC
1、JDBC:
(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API。JDBC是Java访问数据库的标准规范,可以为不同的关系型数据库提供统一访问,它由一组用Java语言编写的接口(大部分)和类组成。
2、JDBC驱动:
JDBC需要连接驱动,驱动是两个设备要进行通信,满足一定通信数据格式,数据格式由设备提供商规定,设备提供商为设备提供驱动软件,通过软件可以与该设备进行通信。
3、JDBC规范(掌握四个核心对象):
DriverManager:用于注册驱动
Connection: 表示与数据库创建的连接
Statement: 操作数据库sql语句的对象
ResultSet: 结果集或一张虚拟表
图解:
4、JDBC原理
Java提供访问数据库规范称为JDBC,而生产厂商提供规范的实现类称为驱动。
JDBC是接口,驱动是接口的实现,没有驱动将无法完成数据库连接,从而不能操作数据库!每个数据库厂商都需要提供自己的驱动,用来连接自己公司的数据库,也就是说驱动一般都由数据库生成厂商提供。
接下来我们学的mysql连接jar包为:mysql-connector-java-8.0.11.jar
5、开发步骤:
注册驱动、建立连接、操作数据 、释放资源
6、API详解:
6.1、API详解:注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());不建议使用
原因有2个:
>导致驱动被注册2次。
>强烈依赖数据库的驱动jar
解决办法:
Class.forName("com.mysql.jdbc.Driver");
6.2、API详解:获得链接
static Connection getConnection(String url, String user, String password)
试图建立到给定数据库 URL 的连接。
参数说明:url 需要连接数据库的位置(网址) user用户名 password 密码
例如:getConnection("jdbc:mysql://localhost:3306/day06", "root", "root");
URL:SUN公司与数据库厂商之间的一种协议。
jdbc:mysql://localhost:3306/day06
协议 子协议 IP : 端口号 数据库
mysql: jdbc:mysql://localhost:3306/day04或者jdbc:mysql:///day14(默认本机连接)
oracle数据库: jdbc:oracle:thin:@localhost:1521:sid
特别注意 : MySQL 驱动 8 版本之后关于 driverClass 与 url 参数的书写变化 :
jdbc:mysql://localhost:3306/day04?serverTimezone=UTC&characterEncoding=utf-8
6.3、java.sql.Connection接口:一个连接
接口的实现在数据库驱动中。所有与数据库交互都是基于连接对象的。
Statement createStatement(); //创建操作sql语句的对象
6.4、API详解:java.sql.Statement接口: 操作sql语句,并返回相应结果
String sql = "SQL语句";
获取Statement语句执行平台:Statement stmt = conn.createStatement();
常用方法:
-
- int executeUpdate(String sql); --执行insert update delete语句.
- ResultSet executeQuery(String sql); --执行select语句.
- boolean execute(String sql); --仅当执行select并且有结果时才返回true,执行其他的语句返回false.
6.5、API详解:处理结果集(注:执行insert、update、delete无需处理)
ResultSet实际上就是一张二维的表格,我们可以调用其boolean next()方法指向某行记录,当第一次调用next()方法时,便指向第一行记录的位置,这时就可以使用ResultSet提供的getXXX(“列名”)来获取表里指定列的数据:
rs.next();//指向第一行
rs.getInt(“name”);//获取name列的数据
常用方法:
- Object getObject(int index) / Object getObject(String name) 获得任意对象
- String getString(int index)/ String getString(String name) 获得字符串
6.7、API详解:释放资源
与IO流一样,使用后的东西都需要关闭!关闭的顺序是先得到的后关闭,后得到的先关闭。
rs.close();
stmt.close();
con.close();
二、JDBC工具类(重点)
配置文件 模块/src/jdbc.properties 项目根路径:
driverClass = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3306/day04?serverTimezone=UTC&characterEncoding=UTF-8
username = root
password = sswer
JDBC工具类:
// 软编码 : 将数据写在配置文件中. 程序运行阶段动态读取配置文件中的信息
/*
静态代码块的特点 :
1. 类加载时, 自动执行静态代码块.
2. 静态静态块仅会被执行一次, 因为类只会被虚拟机加载一次.
*/
public class JDBCUtils {
// 属性 (数据)
// 静态属性如果使用 final 修饰, 还可以在 `静态代码块中` 实现赋值
private static final String driverClass;
private static final String url;
private static final String username;
private static final String password;
// 静态代码块 :
static {
// 1. 创建一个 Properties 对象.
Properties prop = new Properties();
try {
// 2. 加载配置文件数据到 prop 对象中
prop.load(new FileReader("jdbc.properties"));
// 3. 如果加载成功, 为静态属性赋值
driverClass = prop.getProperty("driverClass");
url = prop.getProperty("url");
username = prop.getProperty("username");
password = prop.getProperty("password");
// 加载驱动
loadDriver();
} catch (IOException e) {
// 注意 : 配置文件如果加载失败, 直接抛出一个运行时异常
throw new RuntimeException("配置文件加载失败!");
}
}
// 1. 加载驱动
private static void loadDriver() {
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
// 说明 : 如果驱动加载失败, 之后的所有操作就无需继续执行了...
throw new RuntimeException("驱动加载失败!");
}
}
// 2. 获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
// 3. 释放资源
public static void release(Connection conn, Statement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null; // clear to let GC do its work
}
// 调用下面的方法实现 conn, stmt
release(conn, stmt);
}
public static void release(Connection conn, Statement stmt) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
测试类:
@Test
public void test1() {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1. 获取连接
conn = JDBCUtils.getConnection();
// 2. 操作数据
String sql = "select * from user where id < 10;";
stmt = conn.createStatement();
// Statement 执行对象.
// 作用1: 将 Java语言的字符串转换为 SQL 指令
// 作用2 : 将 SQL 指令交给 MySQL 底层执行.
rs = stmt.executeQuery(sql);
// 遍历结果集对象
while (rs.next()) {
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
String email = rs.getString("email");
System.out.println(id + " : " + username + " : " + password + " : " + email);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 3. 释放资源
JDBCUtils.release(conn, stmt, rs);
}
}
@Test
public void test2() {
Connection conn = null;
Statement stmt = null;
try {
// 1. 获取连接
conn = JDBCUtils.getConnection();
// 2. 操作数据
String sql = "update user set username='赵六', email='[email protected]' where id = 4;";
stmt = conn.createStatement();
int count = stmt.executeUpdate(sql);
System.out.println("count = " + count);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 3. 释放资源
JDBCUtils.release(conn, stmt);
}
}
三、SQL注入
由于没有对用户输入进行充分检查,而SQL又是拼接而成,在用户输入参数时,在参数中添加一些SQL 关键字,达到改变SQL运行结果的目的,也可以完成恶意攻击。
String sql = select * from user where username ='' and password ='' ;
例如:
A、输入 username: zhangsan' or '1'='1 password 随意
select * from user where username ='zhangsan' or '1'='1' and password ='';
* and 优先级 执行 高于 or
B、在SQL添加 -- 是mysql的注释 输入 username: zhangsan' -- password 随意
select * from user where username ='zhangsan' -- ' and password ='' ;
代码如下:
public class LoginTest1 {
public static void main(String[] args) {
// 1. 接收用户数据 [网页文本框中输入 (字符串)]
Scanner sc = new Scanner(System.in);
System.out.println("亲, 请输入您的用户名:");
String username = sc.nextLine();
System.out.println("亲, 请输入您的密码 :");
String password = sc.nextLine();
sc.close();
// 定义需要释放资源的对象
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 2. 建立连接
conn = JDBCUtils.getConnection();
// 3. 操作数据
// 参数拼接 :
String sql = "select * from user where username = '"+username+"' and password = '"+password+"';";
stmt = conn.createStatement();
// 步骤一 : 将拼接完成的 Java 字符串转换为 SQL 指令.
// 步骤二 : 将 SQL 指令交给 MySQL 底层执行, 返回接收返回结果.
rs = stmt.executeQuery(sql);
// 说明 : 登录中, 如果获取结果集, 有两种可能性. 要么有, 要么没有, 有的话, 就仅有一条数据, 不可能出现多条.
if (rs.next()) {
// 取出数据.
System.out.println("登录成功, 欢迎您." + rs.getString("email"));
} else {
System.out.println("亲, 您的用户名或密码错误, 登录失败!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 4. 释放资源
JDBCUtils.release(conn, stmt, rs);
}
}
}
为了解决SQL注入问题、JDBC提供了PreparedStatement。用他来处理mysql的CRUB
查询 : (模拟用户登录)
public class LoginTest2 {
public static void main(String[] args) {
// 1. 接收用户数据 [网页文本框中输入 (字符串)]
Scanner sc = new Scanner(System.in);
System.out.println("亲, 请输入您的用户名:");
String username = sc.nextLine();
System.out.println("亲, 请输入您的密码 :");
String password = sc.nextLine();
sc.close();
// 定义需要释放资源的对象
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 2. 建立连接
conn = JDBCUtils.getConnection();
// 3. 操作数据
// ? 表示占位符.
// 步骤一 : 将未拼接的 Java 字符串转换为 SQL 指令. 这条 SQL 指令是不能执行的, 因为缺少参数.
String sql = "select * from user where username = ? and password = ?;";
stmt = conn.prepareStatement(sql); 预编译
// 中间环节 : 将缺少的参数设置到对应的位置.
stmt.setString(1, username);
stmt.setString(2, password);
// 步骤二 : 直接将指令交给 MySQL 底层执行, 并接收返回结果.
rs = stmt.executeQuery();
// 说明 : 登录中, 如果获取结果集, 有两种可能性. 要么有, 要么没有, 有的话, 就仅有一条数据, 不可能出现多条.
if (rs.next()) {
// 取出数据.
System.out.println("登录成功, 欢迎您." + rs.getString("email"));
} else {
System.out.println("亲, 您的用户名或密码错误, 登录失败!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 4. 释放资源
JDBCUtils.release(conn, stmt, rs);
}
}
}
增加 :
@Test
public void insertTest() {
Connection conn = null;
PreparedStatement stmt = null;
try {
// 1. 建立连接
conn = JDBCUtils.getConnection();
// 2. 操作数据
String sql = "insert into user values(?,?,?,?);";
// 步骤一 : 预编译 Java字符串为 SQL 指令, 但是指令不能执行.
stmt = conn.prepareStatement(sql);
// 中间环节 :
// stmt.setObject(1, null); // null != "null"
stmt.setString(1, null);
stmt.setString(2, "tianqi");
stmt.setString(3, "666");
stmt.setString(4, "[email protected]");
// 步骤二 : 直接将 SQL 执行交给数据库底层执行
int count = stmt.executeUpdate();
System.out.println("count = " + count);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 3. 释放资源
JDBCUtils.release(conn, stmt);
}
}
修改 :
@Test
public void updateTest() {
Connection conn = null;
PreparedStatement stmt = null;
try {
// 1. 建立连接
conn = JDBCUtils.getConnection();
// 2. 操作数据
String sql = "update user set username = ?, password = ?, email = ? where id = ?;";
// 步骤一 : 预编译, 将 Java 字符串编译为 SQL 指令
stmt = conn.prepareStatement(sql);
// 中间环节 :
stmt.setString(1, "张三");
stmt.setString(2, "555");
stmt.setString(3, "[email protected]");
stmt.setInt(4, 1);
// 步骤二 : 直接执行编译完成后的 SQL 执行.
int count = stmt.executeUpdate();
System.out.println("count = " + count);
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 3. 释放资源
JDBCUtils.release(conn, stmt);
}
}
删除 :
@Test
public void deleteTest() {
Connection conn = null;
PreparedStatement stmt = null;
try {
// 1. 建立连接
conn = JDBCUtils.getConnection();
// 2. 操作数据
String sql = "delete from user where id = ?;";
// 步骤一 : 实现预编译
stmt = conn.prepareStatement(sql);
// 中间环节 : 设置参数
stmt.setInt(1, 7);
// 步骤二 : 直接执行 sql 指令
int count = stmt.executeUpdate();
System.out.println("count = " + count);
} catch (SQLException e) {
} finally {
// 3. 释放资源
JDBCUtils.release(conn, stmt);
}
}
总结:JDBC工具类、SQL注入重点