JDBC,即Java Database Connectivity,java数据库连接。是一种用于执行SQL语句的Java API,它是 Java 中的数据库连接规范。这个API由 java.sql.* , javax.sql.* 包中的一些类和接口组成,它为Java
开发人员操作数据库提供了一个标准的API,可以为多种关系数据库提供统一访问
JDBC 为多种关系数据库提供了统一访问方式,作为特定厂商数据库访问API的一种高级抽象,它主要包含一些通用的接口类。
JDBC访问数据库层次结构:

JDBC优势:
// 加载JDBC驱动程序:反射,这样调用初始化com.mysql.jdbc.Driver类,即将该类加载到JVM方法
区,并执行该类的静态方法块、静态属性。
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test?
user=root&password=root&useUnicode=true&characterEncoding=UTF-8");
//MySQL数据连接的URL参数格式如下:
jdbc:mysql://服务器地址:端口/数据库名?参数名=参数值
Statement statement = connection.createStatement();
ResultSet resultSet= statement.executeQuery(
"select id, sn, name, qq_mail, classes_id from student");
while (resultSet.next()) {
int id = resultSet.getInt("id");
String sn = resultSet.getString("sn");
String name = resultSet.getString("name");
int classesId = resultSet.getInt("classes_id");
System.out.println(String.format("Student: id=%d, sn=%s, name=%s,
classesId=%s", id, sn, name, classesId));
}
//关闭结果集
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭命令
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//关闭连接命令
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
在Java JDBC编程中对数据库的操作均使用JDK自带的API统一处理,通常与特定数据库的驱动类是完全解耦的。所以掌握Java JDBC API (位于 java.sql 包下) 即可掌握Java数据库编程。
网络通信过程中,有 “有连接” 和 “无连接” 两种方式,数据库这里的通信方式采用的是有连接的方式。
优点:能够在通信之前,先“投石问路”先看看通信的链路是否畅通。
缺点:连接需要进行管理,尤其是不用的连接,要记得及时释放。
Connection接口实现类由数据库提供,获取Connection对象通常有两种方式:
// 加载JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 创建数据库连接
Connection connection = DriverManager.getConnection(url);
// 1. 使用 DataSource 描述 MySQL 服务器的位置.
// IP 地址
DataSource dataSource = new MysqlDataSource();
// 端口号
((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java104?characterEncoding=utf8&useSSL=false");
// 用户名
((MysqlDataSource)dataSource).setUser("root");
// 密码
((MysqlDataSource)dataSource).setPassword("root");
// 2. 和数据库服务器建立连接
Connection connection = dataSource.getConnection();
Statement对象主要是将SQL语句发送到数据库中。JDBC API中主要提供了三种Statement对象。
Statement:
PreparedStatement:
CallableStatement:
实际开发中最常用的是 PreparedStatement 对象。
主要掌握两种执行 SQL 的方法:
ResultSet 对象它被称为结果集,它代表符合 SQL 语句条件的所有行,并且它通过一套 getXXX 方法提供了对这些行中数据的访问。
ResultSet 里的数据一行一行排列,每行有多个字段,并且有一个记录指针,指针所指的数据行叫做当
前数据行,我们只能来操作当前的数据行。我们如果想要取得某一条记录,就要使用 ResultSet 的next() 方法 ,如果我们想要得到 ResultSet 里的所有记录,就应该使用 while 循环。
import com.mysql.cj.jdbc.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class JDBCInsert {
public static void main(String[] args) throws SQLException {
// 1. 使用 DataSource 描述 MySQL 服务器的位置.
// IP 地址
DataSource dataSource = new MysqlDataSource();
// 端口号
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java104?characterEncoding=utf8&useSSL=false");
// 用户名
((MysqlDataSource) dataSource).setUser("root");
// 密码
((MysqlDataSource) dataSource).setPassword("root");
// 2. 和数据库服务器建立连接
Connection connection = dataSource.getConnection();
// 3. 构造 SQL 语句, JDBC 操作数据库,本质仍然是通过 SQL 来描述数据库操作
// 例如,进行一个插入数据的操作
// 直接用 String 格式的 SQL 还不行,还需要搭配一个 特殊的类
Scanner scanner = new Scanner(System.in);
System.out.println("请输入学号:");
int num = scanner.nextInt();
System.out.println("请输入姓名:");
String name = scanner.next();
String sql = "insert into student values(?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1,num);
statement.setString(2,name);
// 4. 执行 SQL 语句,insert, update, delete 都是通过 executeUpdate 来进行的
// select 则是通过 executeQuety 来执行的
// executeUpdate 的返回值是一个 整数 表示这个操作影响到几行
int n = statement.executeUpdate();
System.out.println("n = " + n);
// 5. 断开连接,释放资源
statement.close();
connection.close();
}
}
import com.mysql.cj.jdbc.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class JDBCUpdate {
public static void main(String[] args) throws SQLException {
// 实现数据库的修改操作,和插入非常相识
// 只是这里构造的 SQL 是 update 语句
// 1. 构造数据源
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java104?characterEncoding=utf8&useSSL=false");
((MysqlDataSource) dataSource).setUser("root");
((MysqlDataSource) dataSource).setPassword("root");
// 2. 和数据库建立连接
Connection connection = dataSource.getConnection();
// 3. 用户输入,要修改的 id 和 修改后的名字
Scanner scanner = new Scanner(System.in);
System.out.println("请输入你要修改的同学学号:");
int id = scanner.nextInt();
System.out.println("请输入修改后的同学姓名:");
// next 读到空白符(空格,制表符,翻页符,换行符,回车符,垂直制表符.....)
// nextLine 读到换行符
String name = scanner.next();
// 4. 构造 SQL 语句
String sql = "update student set name = ? where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1,name);
statement.setInt(2,id);
// 5. 执行 SQL
int n = statement.executeUpdate();
System.out.println("n = " + n);
// 6. 关闭连接,释放资源
statement.close();
connection.close();
}
}
import com.mysql.cj.jdbc.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class JDBCDelete {
public static void main(String[] args) throws SQLException {
// 1. 构造数据源
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java104?characterEncoding=utf8&useSSL=false");
((MysqlDataSource) dataSource).setUser("root");
((MysqlDataSource) dataSource).setPassword("root");
// 2. 建立连接
Connection connection = dataSource.getConnection();
// 3. 输入要删除的内容
Scanner scanner = new Scanner(System.in);
System.out.println("请输入要删除的学生 id:");
int id = scanner.nextInt();
// 4. 构造 SQL
String sql = "delete from student where id = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
// 5. 执行 SQL
int n = statement.executeUpdate();
System.out.println("n = " + n);
// 6. 关闭连接,释放资源
statement.close();
connection.close();
}
}
import com.mysql.cj.jdbc.MysqlDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class JDBCSelect {
public static void main(String[] args) throws SQLException {
// 1. 构造数据源
DataSource dataSource = new MysqlDataSource();
((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java104?characterEncoding=utf8&useSSL=false");
((MysqlDataSource) dataSource).setUser("root");
((MysqlDataSource) dataSource).setPassword("root");
// 2. 建立连接
Connection connection = dataSource.getConnection();
// 3. 输入要的内容
// 4. 构造 SQL
String sql = "select * from student";
PreparedStatement statement = connection.prepareStatement(sql);
// 5. 执行 SQL
// 此处使用executeQuery
// executeUpdate 只能返回一个 int
// executeQuery 返回的是一个 ResultSet 对象, 可以把这个对象视为是一个 “临时表"
ResultSet resultSet = statement.executeQuery();
// 6. 返回临时表,拿到里边的数据
// resultSet 简单的当成一个类似于 “迭代器”
// next 如果没有到达末尾,返回 TRUE
while (resultSet.next()) {
// 通过 ResultSet 里边的 getXXX 方法,来获取指定的列
// 取 id,整数,getInt
int id = resultSet.getInt("id");
// 取 name,String,getString
String name = resultSet.getString("name");
System.out.println(id + ":" + name);
}
// 7. 关闭连接,释放资源
resultSet.close();
statement.close();
connection.close();
}
}
JDBC使用步骤:
// 查询操作
preparedStatement.executeQuery();
// 新增、修改、删除操作
preparedStatement.executeUpdate();
while (resultSet.next()) {
int xxx = resultSet.getInt("xxx");
String yyy= resultSet.getString("yyy");
...
}
try {
if(resultSet != null){
resultSet.close();
}
if(preparedStatement != null){
preparedStatement.close();
}
if(connection != null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("数据库错误");
}