简介
JDBC 就是使用 Java 语言操作关系型数据库的一套 API,它支持同一套 Java 代码操作不同的关系型数据库。
快速入门
在使用不同的数据库之前需要下载导入改数据库的驱动 jar 包,如果是在 IntelliJ IDEA 中的的话需要右键驱动然后点击 Add as Library...。

之后可以选择三个不同的 Level,其中 Module Library 最常用。

然后就可以使用以下代码对数据库进行简单地操作。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//1.register
Class.forName("com.mysql.jdbc.Driver");
//2.get connection
String url = "jdbc:mysql://127.0.0.1:3306/db1?useSSL=false";
String username = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, username, password);
//3. define SQL
String sql1 = "update account set money = 3000 where id = 1";
String sql2 = "update account set money = 3000 where id = 2";
//4.get object that execute sql
Statement stmt = conn.createStatement();
//5.ececute sql
int count1 = -1, count2 = -1;
try {
// start transcation
conn.setAutoCommit(false);
count1 = stmt.executeUpdate(sql1);
if (count1 > 0) {
System.out.println(sql1 + ": execute success!");
}
count2 = stmt.executeUpdate(sql2);
if (count2 > 0) {
System.out.println(sql2 + ": execute success!");
}
// commit
conn.commit();
} catch (Exception throwables) {
// rollback
conn.rollback();
throwables.printStackTrace();
}
//6.process result
System.out.println(count1);
System.out.println(count2);
//7.free resource
stmt.close();
conn.close();
API 详情
DriverManager 作用:注册驱动;获取连接
参考代码1中的代码,第 3 行就是注册驱动,其中会自动调用 DriverManager 里边的函数来注册。第 8 行是获取连接的函数,其中 url 语法格式为 jdbc:mysql://<ip>:<port>/<database>?<useSSL=false>,如果是本地 mysql 的话可以省略 ip 和 port,例如:jdbc:mysql:///db1?useSSL=false,username 和 password 就是 mysql 数据库的用户名和密码。
Connection 作用:获取执行 SQL 的对象;事务管理
获取对象主要有三种方式
1
2
3
Statement createStatement() // 获取普通对象
PrepareStatement prepareStatement() // 获取预编译 SQL 对象,防止 SQL 注入,重要
CallableStatement prepareCall(sql) // 获取执行存储过程对象,不常用
事务管理类似于 MySQL 的事务管理,主要有三个对应的方法。
1
2
3
setAutoCommit(boolean autoCommit) // ture为自动提交事务,false为手动提交事务。JDBC 连接默认为 autoCommit = true,每个 SQL 语句都会自动作为一个独立的事务。
commit() // 事务提交
rollback() // 事务回滚
Statement 作用:执行SQL语句
这个对象有两个常用的函数。
1
2
3
4
5
6
1、int executeUpdate(sql) // 执行DML、DDL语句
// DML 是指修改数据内容的语句;DDL 是修改表结构、创建表的语句
// 执行 DML 时会返回影响的行数;执行 DDL 时执行成功也有可能返回 0
2、ResultSet executeQuery(sql) // 执行DQL语句
// 返回 ResultSet 结果集对象
ResultSet 作用:存储结果集
ResultSet 对象有两个常用的方法用来获取对象中的数据
1. boolean next():将光标从当前位置移动一行,返回值代表当前行是否又数据
2. XXX getXXX(参数):获取当前行指定列的数据,参数为指定的列,可以为列名或者索引,索引从1开始。XXX表示所获取列的元素类型,可以为Int或String等。
1
2
3
4
5
6
ResultSet rs = stmt.executeQuery("select * from account");
while (rs.next()) {
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}
PreparedStatement 作用:继承自 Statement,预编译 SQL 语句;防止 SQL 注入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/db1?useSSL=false&useServerPrepStmts=true";
String username = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, username, password);
String un = "xiaolan";
String pw = "' or '1' = '1";
String sql = "select * from accounts where username = ? and password = ?";
// String sql = "select * from accounts where username = \'"+un+"\' and password = \'"+pw+"\'";
System.out.println(sql);
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, un);
pstmt.setString(2, pw);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
System.out.println("success");
} else {
System.out.println("fail");
}
pstmt.close();
conn.close();
代码第二行最后的参数是开启预编译,开启预编译可以提高 SQL 语句执行效率,不开启预编译也可以防止 SQL 注入。
连接池
标准接口:DataSource,SUN官方提供的数据库连接池标准接口,由第三方组织实现此接口。
常见的数据库连接池实现:
- DBCP
- C3P0
- Druid
Druid 是 Java 语言最好的数据库连接池之一。
附录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 创建数据库
create database db1;
use db1;
create table account(
id int primary key,
name varchar(50) not null,
money float
);
insert into account (id, name, money) values(1, 'xiaoming', 1000);
insert into account (id, name, money) values(2, 'xiaolan', 2000);
create table accounts(
id int primary key,
username varchar(20),
password varchar(20)
);
insert into accounts values(1, "xiaolan", "1234");