java连接MySql数据库

最近在做一个旧系统数据迁移的项目

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 JDBCUtil {
private String username = "root";
private String password = "xxxx";
private String driver = "com.mysql.jdbc.Driver";

private String url="jdbc:mysql://localhost:3306/xxx?useSSL=true&characterEncoding=utf-8";
/**
* 1. 实现数据库连接的方法
*/
public Connection getConn() {
Connection conn = null;
try {
Class.forName(driver);

conn = (Connection) DriverManager.getConnection(url, username, password);
System.out.println("连接数据库成功.");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}

/**
* 2. 释放数据库连接
*/
public void closeConn(ResultSet rs, PreparedStatement pstm, Connection conn) throws Exception {
if (rs != null) {
rs.close();
}
if (pstm != null) {
pstm.close();
}
if (conn != null) {
conn.close();
}
}
}