db.properties放在src目录下
public class DBUtil {
private static Properties prop = new Properties();
static {
try {
prop.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
//加载数据库驱动(可以省略)
Class.forName(prop.getProperty("driverClassName"));
} catch (Exception e) {
System.out.println("加载db.properties配置文件信息异常....");
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn = null;
try {
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
System.out.println("获取数据库连接异常...");
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn, Statement st,ResultSet rs) {
if (st != null) {
try {
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}