JDBCUtils工具类
package com.utils;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
static {
try {
Properties prop = new Properties();
prop.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
String driver = prop.getProperty("driver");
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void close(Statement stmt, ResultSet rs, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
配置文件
url=jdbc:mysql:///test
user=root
password=root
driver=com.mysql.jdbc.Driver