JDBC 概述

  • 定义:Java Database Connectivity (JDBC) 是 Java 语言操作关系型数据库的一套 API,MyBatis 等框架底层均基于 JDBC。

  • 核心功能:提供数据库连接、SQL 执行、结果集处理等操作接口。


JDBC 操作示例

需求:更改 id=1 的记录的 age2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void test() throws Exception {
// 1. 注册驱动(兼容性建议显式加载)
Class.forName("com.mysql.cj.jdbc.Driver");

// 2. 建立数据库连接
String url = "jdbc:mysql://localhost:3306/web01";
String username = "root";
String password = "1234";
Connection connection = DriverManager.getConnection(url, username, password);

// 3. 创建 SQL 执行对象
Statement statement = connection.createStatement();

// 4. 执行 SQL 更新
int i = statement.executeUpdate("UPDATE user SET age = 2 WHERE id = 1");
System.out.println("SQL 执行完毕,影响的记录数: " + i);

// 5. 释放资源(注意关闭顺序)
statement.close();
connnection.close(); // 注意拼写应为 connection.close();
}

JDBC 使用步骤详解

1. 导入 JDBC 驱动包

  • 方式:通过 Maven 依赖或手动添加 JAR 包(如 mysql-connector-java.jar)。

2. 加载数据库驱动

  • 代码
1
Class.forName("com.mysql.cj.jdbc.Driver"); // 显式加载驱动(兼容性建议)
  • 注意:JDBC 4.0+ 支持自动加载,但显式声明更可靠。

3. 建立数据库连接

  • 方法DriverManager.getConnection()

  • 参数

1
2
3
4
String url = "jdbc:mysql://localhost:3306/db?useSSL=false&serverTimezone=UTC";
String user = "root";
String password = "1234";
Connection conn = DriverManager.getConnection(url, user, password);

4. 创建 Statement 对象

  • 类型

    • Statement:静态 SQL(简单但易引发 SQL 注入)
      1
      Statement stmt = conn.createStatement();
    • PreparedStatement:动态 SQL(推荐,防注入、高性能)
      1
      2
      3
      String sql = "SELECT * FROM users WHERE id = ?";
      PreparedStatement pstmt = conn.prepareStatement(sql);
      pstmt.setInt(1, 1001); // 参数绑定

5. 执行 SQL 语句

  • 查询操作(SELECT):

    1
    ResultSet rs = stmt.executeQuery("SELECT * FROM users");
  • 更新操作(INSERT/UPDATE/DELETE):

    1
    int affectedRows = stmt.executeUpdate("UPDATE users SET name='John' WHERE id=1001");

6. 处理结果集

  • 遍历 ResultSet
1
2
3
4
5
6
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
// 处理其他字段...
}

7. 关闭资源

  • 顺序ResultSet → Statement → Connection

  • 手动关闭

    1
    2
    3
    if (rs != null) rs.close();
    if (stmt != null) stmt.close();
    if (conn != null) conn.close();
  • 自动关闭(推荐 try-with-resources):

    1
    2
    3
    4
    5
    6
    try (Connection conn = DriverManager.getConnection(url, user, password);
    PreparedStatement pstmt = conn.prepareStatement(sql)) {
    // 执行操作
    } catch (SQLException e) {
    e.printStackTrace();
    }

8. 异常处理

  • 捕获 SQLException
    1
    2
    3
    4
    5
    6
    try {
    // JDBC 操作代码
    } catch (SQLException e) {
    e.printStackTrace();
    // 回滚事务等处理
    }

9. 事务控制(可选)

  • 管理事务原子性
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    conn.setAutoCommit(false); // 关闭自动提交
    try {
    // 执行多个操作
    conn.commit(); // 提交事务
    } catch (SQLException e) {
    conn.rollback(); // 回滚事务
    throw e;
    } finally {
    conn.setAutoCommit(true); // 恢复自动提交
    }

Connection 对象核心作用

  1. 创建执行对象

    • Statement / PreparedStatement / CallableStatement
  2. 事务管理

    • setAutoCommit(false):关闭自动提交

    • commit():提交事务

    • rollback():回滚事务

  3. 元数据获取

    java

    复制

    DatabaseMetaData metaData = conn.getMetaData();

  4. 连接状态管理

    • close():释放连接

    • isValid(timeout):检查连接有效性


ResultSet 核心方法

  • next()
    将光标移动到下一行,返回 boolean 表示是否为有效行。

  • getXxx()
    按列名或索引获取数据(如 getInt("id")getString(2))。


注意事项

  1. URL 格式:需指定时区(如 &serverTimezone=UTC)和禁用 SSL(测试环境)。

  2. 资源释放:必须显式关闭资源或使用 try-with-resources。

  3. 拼写检查:示例代码中 connnection.close() 应为 connection.close()(需修正拼写错误)。


预编译SQL

  • 优势一: 可以防止SQL注入,更安全
    SQL注入,通过输入来事先修改的SQL语句

载输入内容时候:比如校验登录的语句时
select count(*) from user where user name = “” && password = “”;

此时如果想要攻击,可以把密码设置成 1” or “1 = 1, 这样代换到原来密码,恒成立故hi被注入

  • 性能更高

mysql底层事先得经过以下几步:
SQL语法解析检查 -》 优化SQL -》 编译SQL, 之后将SQL缓存,每次有新的进来会先从缓冲找,否则加入缓存,之后再执行

使用了预编译性能更高