写了一个Utils工具类,减少每次创建连接和关闭连接的重复代码,使用静态代码块在类加载时自动导入配置和注册驱动。
/*
未使用数据库连接池
*/
public class JDBCUtils {
static String user;
static String password;
static String url;
static {
Properties pro=new Properties();
//通过反射拿到资源包
try {
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
user= pro.getProperty("user");
password = pro.getProperty("password");
url = pro.getProperty("url");
String driver = pro.getProperty("driver");
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
//关闭连接
public static void closeResources(Connection connection, Statement statement, ResultSet resultSet){
if (connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}