properties 文件连接数据库
- 创建db.properties文件
#数据库封装成外部文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/j11?serverTimezone=Hongkong&useUnicode=true&characterEncoding=utf8&useSSL=false
#url=jdbc:mysql://localhost/j11?useSSL=false&CharacterEncoding=UTF-8&server=TUC
user=root
password=19990507
2.创建DButil
package com.xmx.util;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
//封装数据库的连接
public class DButil {
private static String drivername;
private static String url;
private static String username;
private static String pwd;
//静态代码块
static {
//1 读 db.properties
try {
InputStream is = DButil.class.getClassLoader()
.getResourceAsStream("com/xmx/util/db.properties");
//2 属性集的类
Properties p = new Properties();
p.load(is);
drivername = p.getProperty("driver");
url = p.getProperty("url");
username = p.getProperty("user");
pwd = p.getProperty("password");
} catch (Exception e) {
e.printStackTrace();
System.out.println("db.properties 参数出错.....");
}
}
//连接
public static Connection getConn() {
try {
//注册驱动
Class.forName(drivername);
//获取连接
return DriverManager.getConnection(url, username, pwd);
} catch (Exception throwables) {
throwables.printStackTrace();
}
return null;
}
// 释放是资源
public static void closeConn(Connection conn, PreparedStatement pst, ResultSet rs) {
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}