Repository navigation
Expand file tree
/
Copy pathJDBCUtil.java
More file actions
executable file
·95 lines (91 loc) · 2.47 KB
/
Copy pathJDBCUtil.java
File metadata and controls
executable file
·95 lines (91 loc) · 2.47 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
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
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtil {
// private static final String URL = "jdbc:mysql://localhost:3306/gt?useUnicode=true&characterEncoding=utf8";
// private static final String USERNAME = "root";
// private static final String PASSWORD = "123456";
private static final String URL = "jdbc:mysql://rm-uf6533mo112otpf4so.mysql.rds.aliyuncs.com:3306/gt?useUnicode=true&characterEncoding=utf8";
private static final String USERNAME = "rootadmin";
private static final String PASSWORD = "rootAdmin@123";
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static Connection conn =null;
private static Statement stat=null;
private static ResultSet rs =null;
// 1.注册驱动
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 数据库对象连接使用的
public Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
// 关闭资源使用
public void close() {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//查询使用
public ResultSet select(String sql) {
// 2.获取数据库连接对象
try {
conn = getConnection();
// 3.获取执行sql语句使用的对象--statement
stat = conn.createStatement();
// 4.执行sql语句
rs = stat.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
//增删改的通用方法
public int execution(String sql) {
// 2.获取数据库连接对象
int i = 0;
try {
conn =getConnection();
// 3.获取执行sql语句使用的对象--statement
stat = conn.createStatement();
// 4.执行sql语句
i = stat.executeUpdate(sql);// 返回值表示数据库中受影响的行数
} catch (SQLException e) {
e.printStackTrace();
} finally {
close();
}
return i;// 将执行sql后的返回值返回给调用者。
}
}