DBUtil工具类
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class DBUtil {
public static Connection getConnection() throws ClassNotFoundException,
SQLException {
Properties properties = PropertiesUtil.getProperties("config.properties");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
// 因为resultSet , connection等 都继承了 AutoCloseable 所以 这里直接写父类即可,因为多态
public static void close(AutoCloseable obj) {
if (obj != null) {
try {
obj.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
PropertiesUtil工具类
import java.io.IOException;
import java.util.Properties;
public class PropertiesUtil {
private static Properties properties = null;
private PropertiesUtil() {
}
public static Properties getProperties() {
return getProperties("config.properties");
}
public static Properties getProperties(String fileName) {
if (properties == null) {
properties = new Properties();
try {
// PropertiesUtil.class : 获取运行时类(正在运行的类)
// getClassLoader() : 获取类加载器
// getResourceAsStream : 把指定资源转换为流对象
// load : 传入流对象,把对象中数据转换为map存储,间隔符为 = 或 :
properties.load(PropertiesUtil.class.getClassLoader()
.getResourceAsStream(fileName));
} catch (IOException e) {
e.printStackTrace();
}
}
return properties;
}
}