-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJDBCUtils_Use.java
More file actions
62 lines (57 loc) · 2.07 KB
/
JDBCUtils_Use.java
File metadata and controls
62 lines (57 loc) · 2.07 KB
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
55
56
57
58
59
60
61
62
package com.charlie.jdbc.utils;
import org.junit.Test;
import java.sql.*;
/**
* 演示如何使用 JDBCUtils 工具类,完成dml和select
*/
public class JDBCUtils_Use {
@Test
public void testDML() { // insert, update, delete
// 1. 得到连接
Connection connection = null;
// 2. 编写sql
String sql = "update actor set name = ? where id = ?;";
// String sql = "insert into actor values (null, ?, null, null, ?)";
// 3. 创建 PreparedStatement 对象
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
// 给占位符赋值
preparedStatement.setString(1, "李达康");
preparedStatement.setInt(2, 2);
// 执行
preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
// 关闭资源
JDBCUtils.close(null, preparedStatement, connection);
}
}
@Test
public void testSelect() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet set = null;
try {
connection = JDBCUtils.getConnection();
String sql = "select * from actor;";
preparedStatement = connection.prepareStatement(sql);
set = preparedStatement.executeQuery();
while (set.next()) {
int id = set.getInt("id");
String name = set.getString("name");
String gender = set.getString("gender");
Date date = set.getDate("borndate");
String phone = set.getString("phone");
System.out.println(id + "\t" + name + "\t" + gender + "\t" + date + "\t" + phone);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
// 关闭资源
JDBCUtils.close(set, preparedStatement, connection);
}
}
}