public class DBUtils {
// 不变的东西
private static String driverclass = "com.mysql.cj.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/test";
private static String user = "root";
private static String password = "123456";
// static语句块,该类被加载的时候会被执行且只执行一次,驱动注册
static {
try {
Class.forName(driverclass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 建立连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
// 释放连接
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}