JDBC工具类

目的:简化代码书写

实现:

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
* JDBC工具类
*/
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;

/**
* 读取文件,只需要读取一次就可以拿到所有值,使用静态代码块
*/
static {
try {
//读取文件,获取值
//创建Properties
Properties properties = new Properties();
//获取src路径下的文件方式---->ClassLoader 类加载器
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL resource = classLoader.getResource("jdbc.properties");
String path = resource.getPath();
// System.out.println(path);

//加载文件
properties.load(new FileReader(path));
//读取文件 赋值
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
driver = properties.getProperty("driver");

//注册驱动
Class.forName(driver);



} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}


}

/**
* 获取连接
* @return连接对象
*
* 通过配置文件传递参数
* 配置文件:
* jdbc.properties
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}

/**
* 释放资源
* @param statement
* @param connection
*/
public static void close(Statement statement, Connection connection){

if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}

if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}

/**
* 释放资源
* @param resultSet
* @param statement
* @param connection
*/
public static void close(ResultSet resultSet,Statement statement, Connection connection){

if (resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}

if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}

if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}

创建配置文件:jdbc.properties

1
2
3
4
url=jdbc:mysql:///test2?&useSSL=false&serverTimezone=UTC
user=root
password=1234
driver=com.mysql.cj.jdbc.Driver

在使用JDBC创建项目时就能使用工具类调用方法来代替大串的代码,并且改变数据库的连接只需要改动配置文件,不需要改动代码。