JDBC:Java Database Connectivity,Java 数据库连接
需要 jar 包支持:
java.sql
javax.sql
mysql-connector-java(连接驱动,必须导入)
在 MySQL 先建个 jdbc 数据库后 USE jdbc;
执行后再 CREATE TABLE 创建表
执行后插入数据 INSERT INTO
USE jdbc;
create table users(
id int primary key,
`name` varchar(40),
`password` varchar(40),
email varchar(60),
birthday date
);
insert into users(id,`name`,`password`,email,birthday)
values(1,'张三1','123','zs1@qq.com','2024-06-30');
insert into users(id,`name`,`password`,email,birthday)
values(2,'张三2','123','zs2@qq.com','2024-06-30');
insert into users(id,`name`,`password`,email,birthday)
values(3,'张三3','123','zs3@qq.com','2024-06-30');
insert into users(id,`name`,`password`,email,birthday)
values(4,'张三4','123','zs4@qq.com','2024-06-30');
select * from users;
点这个执行
查询结果:
pom.xml 导入数据库依赖:
<!-- 连接数据库 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
IDEA 连接数据库(没有的去 Settings Plugins 搜索 DataBase 下载)
JDBC 固定步骤:
1.加载驱动
2.连接数据库
3.向数据库发送 SQL 对象 Statement
4.编写 SQL
5.执行 SQL
6.关闭连接
代码如下:
package com.demo.jdbc;
import java.sql.*;
public class Demo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息 useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
String username = "root";
String password = "root";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
Connection connection = DriverManager.getConnection(url, username, password);
//3.向数据库发送SQL对象Statement:CRUD:create添加 read读取 update修改 delete删除
Statement statement = connection.createStatement();
//4.编写SQL
String sql = "select * from users";
//5.执行查询SQL,返回一个ResultSet结果集
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("name="+resultSet.getObject("name"));
System.out.println("password="+resultSet.getObject("password"));
System.out.println("email="+resultSet.getObject("email"));
System.out.println("birthday="+resultSet.getObject("birthday"));
}
//6.关闭连接,释放资源,先开后关
resultSet.close();
statement.close();
connection.close();
}
}
编写 SQL 时,因为引号里没有显示,可以在 IDEA 提供连接的数据库里编写 sql 语句然后复制过去
代码执行效果如下:
同理,删除语句:
delete from users where id = 4;
增删改都用 executeUpdate,int 型是受影响的行数
int i = statement.executeUpdate(sql);
JDBC 事务:
要么都成功,要么都失败
ACID 原则:保证数据的安全
原子性 (Atomicity)、 一致性(Consistency)、隔离性(Isolation) 、 持久性(Durability)
Junit 单元测试依赖:
(从 导入 jar 包 复制过来的 junit 把 <scope> 这行删除,不然没有 @Test 注解)
<!-- 单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
</dependency>
@Test 注解只在方法上有效,不需要 main 方法,只要加了这个注解的方法就能运行
public class Test {
@org.junit.Test
public void test(){
System.out.println("Hello");
}
}
举个事务的例子:转账
建表,插入数据
use jdbc;
create table account(
id int primary key auto_increment,
`name` varchar(40),
money float
);
insert into account(`name`,money) value('A',100);
insert into account(`name`,money) value('B',100);
通知数据库开启事务,false开启
connection.setAutoCommit(false);
代码如下:
package com.demo.jdbc;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JdbcDemo {
@Test
public void test(){
//配置信息 useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
String username = "root";
String password = "root";
Connection connection = null;
try {
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库
connection = DriverManager.getConnection(url, username, password);
//3.通知数据库开启事务,false开启
connection.setAutoCommit(false);
String sql = "update account set money = money-10 where name = 'A'";
connection.prepareStatement(sql).executeUpdate();
String sql1 = "update account set money = money+10 where name = 'B'";
connection.prepareStatement(sql1).executeUpdate();
//提交事务
connection.commit();
System.out.println("success");
} catch (Exception e) {
try {
//如果出现异常,就通知数据库回滚事务
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}