配置文件:jdbc.properties
url=jdbc:mysql:/
username=root
password=root
driver=com.mysql.jdbc.Driver
工具类:JDBCUtils
public class JDBCUtils {
private static String url;
private static String username;
private static String password;
static {
Properties pro = new Properties();
String path = JDBCUtils.class.getClassLoader().getResource("jdbc.properties").getPath();
try {
pro.load(new FileReader(path));
url = pro.getProperty("url");
username = pro.getProperty("username");
password = pro.getProperty("password");
String driver = pro.getProperty("driver");
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
public static void close(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}