JDBC详解

JDBC详解

一、什么是JDBC

JDBC:Java连接数据库!
需要的jar包支持

  • java.sql
  • javax.sql
  • mysql-connecter-java…连接驱动(必须要导入)

二、实验环境搭建

1. SQL语句创建表

1
2
3
4
5
6
7
8
9
10
11
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, '张三', '123456', 'zs@qq.com', '2000-01-01' );
INSERT INTO users ( id, `name`, `password`, email, birthday )
VALUES
( 2, '李四', '123456', 'ls@qq.com', '2000-01-01' );
INSERT INTO users ( id, `name`, `password`, email, birthday )
VALUES
( 3, '王五', '123456', 'ww@qq.com', '2000-01-01' );∞
SELECT * FROM users;

2. 导入数据库依赖

1
2
3
4
5
6
<!--mysql的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>

3. 在IDEA中配置数据库

4. JDBC固定步骤

  1. 加载驱动
  2. 连接数据库,代表数据库
  3. 向数据库发送SQL的对象Statement,PreparedStatement :CRUD
  4. 编写SQL(根据业务,不同的SQL)
  5. 执行查询SQL,返回一个ResultSet结果集
  6. 关闭连接,释放资源(一定要做) 先开后关

5. 直接执行SQL

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
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//userUnicode=true&characterEncoding=utf-8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?userUnicode=true&characterEncoding=utf-8&useSSL=false";
String username="root";
String password="nc20011019";
//1. 加载驱动
Class.forName("com.mysql.jdbc.Driver");

//2. 连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);

//3. 向数据库发送SQL的对象Statement:CRUD
Statement statement = connection.createStatement();

//4. 编写SQL
String sql = "SELECT * FROM users;";

//5. 执行查询SQL,返回一个ResultSet结果集
ResultSet rs = statement.executeQuery(sql);

while (rs.next()){
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"));
}
//6. 关闭连接,释放资源(一定要做) 先开后关

rs.close();
statement.close();
connection.close();

}

6. 预编译执行SQL

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
public class testJDBC02 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//userUnicode=true&characterEncoding=utf-8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?userUnicode=true&characterEncoding=utf-8&useSSL=false";
String username="root";
String password="nc20011019";
//1. 加载驱动
Class.forName("com.mysql.jdbc.Driver");

//2. 连接数据库,代表数据库
Connection connection = DriverManager.getConnection(url, username, password);

//3. 编写SQL
String sql = "insert into users (id, name, password, email, birthday) value (?,?,?,?,?);";

//4. 预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,4); //给第一个占位符'?'赋值为4;
preparedStatement.setString(2,"王二麻"); //给第二个占位符'?'赋值为"王二麻";
preparedStatement.setString(3,"123456"); //给第三个占位符'?'赋值为"123456";
preparedStatement.setString(4,"wem@qq.com"); //给第四个占位符'?'赋值为"wem@qq.com";
preparedStatement.setDate(5,new Date(new java.util.Date().getTime())); //给第五个占位符'?'赋值为new Date(new java.util.Date().getTime());第一个Date是SQL的Date第二个才是java的Date


//5. 执行SQL
int i = preparedStatement.executeUpdate();

if (i>0){
System.out.println("插入成功");
}
//6. 关闭连接,释放资源(一定要做) 先开后关
preparedStatement.close();
connection.close();

}
}

预编译的SQL,一次编译后,在后面直接执行就可,不需要再次传递sql语句.
int i = preparedStatement.executeUpdate();

三、事务

要么都成功,要么都失败!
ACID原则:保证数据的安全。

1
2
3
4
5
6
7
8
9
10
11
开启事务
事务提交 commit()
事务回滚 roallback()
关闭事务

转账:
A:1000
B:1000

A(900) --100--> B(1100)
A转给B 100 假如服务器崩了,事务回滚

1. Junit单元测试(可以免写main方法!)

依赖

1
2
3
4
5
6
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>/</scope>
</dependency>
1
2
3
4
5
6
7
8
9
package com.nichu.test;

import org.junit.Test;
public class testJDBC03 {
@Test //在方法上加入@Test注解,该方法就可执行!
public void test(){
System.out.println("Hello");
}
}

2. 事务实现转账

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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public class testJDBC03 {
@Test
public void test() {
//配置信息
//userUnicode=true&characterEncoding=utf-8 解决中文乱码
String url = "jdbc:mysql://localhost:3306/jdbc?userUnicode=true&characterEncoding=utf-8&useSSL=false";
String username="root";
String password="nc20011019";

Connection connection = null;
try {
//1. 加载驱动
Class.forName("com.mysql.jdbc.Driver");


//2. 连接数据库,代表数据库
connection = DriverManager.getConnection(url, username, password);

//3. 通知数据库开启事务,false开启
connection.setAutoCommit(false);


//3. 编写SQL
String sql = "UPDATE account set money=money-100 where name = '王五';";
connection.prepareStatement(sql).executeUpdate();

//制造错误
//int i=1/0;
String sql2 = "UPDATE account set money=money+100 where name = '赵四';";
connection.prepareStatement(sql2).executeUpdate();

//4. 以上语句都执行成功了就提交事务
connection.commit();
System.out.println("转账成功!!");
} catch (Exception e) {
try {
//5. 如果出现异常执行回滚事务
connection.rollback();
System.out.println("转账失败!!");
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
}finally {
//6. 关闭连接,释放资源(一定要做) 先开后关
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}

}
}

注意:要开启通知数据库开启事务connection.setAutoCommit(false);

-------------本文结束感谢您的阅读-------------