jdbc.properties文件
driver=com.mysql.cj.jdbc.Driver //Mysql5 是com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名字?serverTimezone=Asia/Shanghai
username=数据库用户名
password=数据库密码
JDBC工具类
/**
* JDBC的工具类
*/
public class DButil {
//使用ResourceBundle,这样使用别的数据库不用在源代码修改,而在jdbc.properties进行修改
private static ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
private static String driver = bundle.getString("driver");
private static String url = bundle.getString("url");
private static String username = bundle.getString("username");
private static String password = bundle.getString("password");
private DButil() {//工具类属性私有化
}
static {//在类加载的时候完成注册驱动
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//连接数据库
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
//关闭资源
public static void close(Connection conn, Statement ps, ResultSet rs){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}