package com.gh;
import java.io.FileReader;
import java.io.Reader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public final class JDBCUtils {
private static String driver;
private static String url;
private static String user;
private static String password;
static {
// 加载db.properties配置文件
Properties properties = new Properties();
try {
//获取配置文件的path
ClassLoader loader = JDBCUtils.class.getClassLoader();
URL url = loader.getResource("db.properties");
String path = url.getPath();
Reader inStream = new FileReader(path);
properties.load(inStream );
} catch (Exception e1) {
e1.printStackTrace();
}
//拿到配置文件的数据
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception {
// 获取连接
Connection conn = DriverManager.getConnection(url, user, password);
return conn;
}
//释放资源
public static void release(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
st = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
conn = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
db.properties:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/表名
user=mysql的用户名
password=mysql的密码