我们可以把 JDBC 的运作过程想象成**"寄信"或者"连接服务"**的过程。这四个核心接口按逻辑顺序协作,共同完成了从连接数据库到获取数据的全过程:
1. DriverManager(驱动管理器):就像"中介或入口"
它是 JDBC 的入口。负责加载数据库驱动程序,并根据你提供的 URL、用户名和密码,寻找合适的驱动来建立连接。
- 任务:管理驱动,建立连接。
2. Connection(数据库连接对象):就像"电话线或通道"
通过 DriverManager 成功连接后,你会得到一个 Connection 对象。它代表了与特定数据库的一次会话(Session)。如果没有连接,后续所有的操作都无法执行。
- 任务:维护连接状态,开启事务。
3. Statement(指令携带者):就像"邮寄的信件"
通过 Connection 创建 Statement 对象。它是用来向数据库发送 SQL 语句的载体。
- 常用写法 :使用
PreparedStatement(Statement的子接口)来防止 SQL 注入。 - 任务:将 SQL 发送到数据库并执行。
4. ResultSet(结果集):就像"收到的回信"
当你执行查询类 SQL(如 SELECT)时,数据库会返回大量数据,这些数据就存储在 ResultSet 对象中。你可以像遍历列表一样,从中读取每一行的数据。
- 任务:存储和读取查询结果。
总结:它们的关系流向
整个流程可以用这个顺序来概括:
- DriverManager 建立连接,得到 Connection。
- Connection 创建 Statement。
- Statement 执行 SQL,返回 ResultSet。
- ResultSet 存放结果,供你读取。
简单的代码逻辑示意:
// 1. 获取连接
Connection conn = DriverManager.getConnection(url, user, password);
// 2. 创建发送器
Statement stmt = conn.createStatement();
// 3. 执行查询并获得结果
ResultSet rs = stmt.executeQuery("SELECT * FROM users");
// 4. 处理结果
while (rs.next()) {
System.out.println(rs.getString("name"));
}
希望这个比喻能帮你理清它们的关系!
1.在Linux中创建数据库jdbc_demo和表tb_space
java
$ sudo service mysql start
* Starting MySQL database server mysqld [ OK ]
$ sudo service mysql status
* /usr/bin/mysqladmin Ver 10.0 Distrib 10.6.18-MariaDB, for debian-linux-gnu on x86_64
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Server version 10.6.18-MariaDB-0ubuntu0.22.04.1
Protocol version 10
Connection Localhost via UNIX socket
UNIX socket /run/mysqld/mysqld.sock
Uptime: 28 sec
Threads: 1 Questions: 61 Slow queries: 0 Opens: 33 Open tables: 26 Queries per second avg: 2.178
$ sudo mysql -u root
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 35
Server version: 10.6.18-MariaDB-0ubuntu0.22.04.1 Ubuntu 22.04
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]> CREATE DATABASE IF NOT EXISTS jdbc_demo CHARACTER SET utf8mb4;
Query OK, 1 row affected (0.001 sec)
MariaDB [(none)]> use jdbc_demo
Database changed
MariaDB [jdbc_demo]> CREATE TABLE tb_space(
-> id INT PRIMARY KEY AUTO_INCREMENT,
-> name VARCHAR(40),
-> launchtime DATE
-> );
Query OK, 0 rows affected (0.017 sec)
MariaDB [jdbc_demo]> INSERT INTO tb_space(name,launchtime) VALUES('AA','1970-4-24'),('BB','2003-10-15'),('CC','2007-10-24');
Query OK, 3 rows affected (0.001 sec)
Records: 3 Duplicates: 0 Warnings: 0
MariaDB [jdbc_demo]> SELECT * FROM tb_space;
+----+------+------------+
| id | name | launchtime |
+----+------+------------+
| 1 | AA | 1970-04-24 |
| 2 | BB | 2003-10-15 |
| 3 | CC | 2007-10-24 |
+----+------+------------+
3 rows in set (0.000 sec)
MariaDB [jdbc_demo]>
2.编写JDBC程序
java
import java.sql.*;
public class Example01 {
public static void main(String[] args) throws SQLException {
Connection conn =null;
Statement stmt =null;
ResultSet rs =null;
try {
// 加载并注册数据库驱动程序
Class.forName("com.mysql.cj.jdbc.Driver");
// 通过DriverManager类获取数据库连接
String url = "jdbc:mysql://localhost:3306/jdbc_demo";
String username = "root";
String password = "root";
conn = DriverManager.getConnection(url,username, password);
// 通过Connection对象获取Statement对象
stmt = conn.createStatement();
// 执行SQL语句
String sql = "SELECT * FROM tb_space";
rs = stmt.executeQuery(sql);
// 操作ResultSet结果集
System.out.println("id | name | launchtime");
while (rs.next()) {
int id = rs.getInt("id"); // 通过列名获取指定字段的值
String name = rs.getString("name");
Date launchtime= rs.getDate("launchtime");
System.out.println(id + " | " + name + " | "
+ launchtime);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
if(rs !=null){ rs.close(); }
if(stmt !=null){ stmt.close(); }
if(conn !=null){ conn.close(); }
}
}
}
3.程序执行结果:
java
$ javac -cp /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/mysql-connector-java-5.1.35.jar Example01.java
$ java -cp .:/usr/lib/jvm/java-8-openjdk-amd64/jre/lib/mysql-connector-java-5.1.35.jar Example01
id | name | launchtime
1 | AA | 1970-04-24
2 | BB | 2003-10-15
3 | CC | 2007-10-24