前言:自从大一做了一个图书馆信息管理系统后,就一直没再用JDBC,但JDBC之上的封装库用了不少,然而今天还是想去回顾一下原始的JDBC,于是有了此文。此文学习自B站UP:遇见狂神说的教程。
IDEA + MySQL
pom.xml添加依赖
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.22version>
dependency>
dependencies>
导入数据库,可方便编写SQL语句,IDEA的提示功能很好用。
(不导数据库也可以连接,因为只要开了MySQL的端口,如3306,便可以实现与数据库进程的通信)
数据准备
(注:->忽略即可,自定义字段与MySQL中关键字重复的话,可用``包围)
mysql> CREATE TABLE users(
-> id INT PRIMARY KEY AUTO_INCREMENT,
-> `name` VARCHAR(40),
-> `password` VARCHAR(40),
-> email VARCHAR(60),
-> birthday DATE);
INSERT INTO users(`name`, `password`, email, birthday)
-> VALUES('张三', '123456', '[email protected]', '2000-01-01');
INSERT INTO users(`name`, `password`, email, birthday)
-> VALUES('李四', '123456', '[email protected]', '2000-01-01');
INSERT INTO users(`name`, `password`, email, birthday)
-> VALUES('王五', '123456', '[email protected]', '2000-01-01');
0.配置信息
1.加载驱动
2.创建连接数据库的的对象,Connection的对象代表数据库
3.创建向数据库发送SQL的对象,Statement / PreparedStatement : CRUD
(注:如果是预编译,则3、4步骤对换顺序)
4.编写SQL
5.执行SQL,得到 ResultSet : 结果集
6.对结果集对象rs进行操作
7.关闭连接,释放资源(先开的后关)
public class TestJdbc {
public static void main(String[] args) {
//0.配置信息
String url = "jdbc:mysql://localhost:3306/kuang?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "";
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//2.创建连接数据库的的对象,Connection的对象代表数据库
Connection connection = null;
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
//3.创建向数据库发送SQL的对象,Statement : CRUD
Statement statement = null;
try {
statement = connection.createStatement();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
//4.编写SQL
String sql = "SELECT * FROM users;";
//5.执行SQL,得到 ResultSet : 结果集
ResultSet rs = null;
try {
rs = statement.executeQuery(sql);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
//6.对结果集对象rs进行操作
while (true) {
try {
if (!rs.next()) {
break;
} else {
System.out.println("id = " + rs.getObject("id"));
System.out.println("name = " + rs.getObject("name"));
System.out.println("password = " + rs.getObject("password"));
System.out.println("email " + rs.getObject("email"));
System.out.println("birthday = " + rs.getObject("birthday"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
//7.关闭连接,释放资源(先开的后关)
try {
rs.close();
statement.close();
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public class TestJdbc2 {
public static void main(String[] args) {
//0.配置信息
String url = "jdbc:mysql://localhost:3306/kuang?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "";
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//2.连接数据库,connection代表数据库
Connection connection = null;
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
//3.编写SQL
String sql_insert = "INSERT INTO users(name, password, email, birthday) VALUES (?, ?, ?, ?);";
//4.预编译 PreparedStatement : CRUD
PreparedStatement preparedStatement = null;
try {
preparedStatement = connection.prepareStatement(sql_insert);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
try {
preparedStatement.setString(1, "zlc");//第i个占位符,赋值为key
preparedStatement.setString(2, "123456");
preparedStatement.setString(3, "[email protected]");
preparedStatement.setDate(4, new Date(System.currentTimeMillis()));
} catch (SQLException throwables) {
throwables.printStackTrace();
}
//5.执行SQL
int i = 0;
try {
i = preparedStatement.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
if (i > 0) {
System.out.println("插入成功~");
}
//7.关闭连接,释放资源(先开的后关)
try {
preparedStatement.close();
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
CREATE TABLE account (
-> id INT PRIMARY KEY AUTO_INCREMENT,
-> `name` VARCHAR(40),
-> money FLOAT);
INSERT INTO account (`name`, money) VALUES ('A', 1000);
INSERT INTO account (`name`, money) VALUES ('B', 1000);
INSERT INTO account (`name`, money) VALUES ('C', 1000);
0.配置信息
1.加载驱动
2.创建连接数据库的的对象,Connection的对象代表数据库
3.事务操作
4.关闭,释放资源(先开的后关)
public class TestJdbc3 {
@Test
public void test() {
//0.配置信息
String url = "jdbc:mysql://localhost:3306/kuang?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "";
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//2.连接数据库,connection代表数据库
Connection connection = null;
try {
connection = DriverManager.getConnection(url, username, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
//3.1 开启事务:通知数据库开启事务,false是开启
//等价于SQL中的 START TRANSACTION;
try {
connection.setAutoCommit(false);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
PreparedStatement preparedStatement1 = null;
PreparedStatement preparedStatement2 = null;
try {
String sql1 = "UPDATE account SET money = money - 100 WHERE name = 'A';";
preparedStatement1 = connection.prepareStatement(sql1);
preparedStatement1.executeUpdate();
//制造错误
int i = 1 / 0;
String sql2 = "UPDATE account SET money = money + 100 WHERE name = 'B';";
preparedStatement2 = connection.prepareStatement(sql2);
preparedStatement2.executeUpdate();
//3.2 事务提交:以上两条sql都执行成功了,则提交事务
connection.commit();
} catch (SQLException throwables) {
//3.3 事务回滚
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
//7.关闭,释放资源(先开的后关)
try {
preparedStatement1.close();
preparedStatement2.close();
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}