封装获取连接、释放资源两个方法。
提供public static Connection getConnection(){}方法。
提供public static void closeAll(Connection conn , Statement sm , ResultSet rs){}方法。
工具类的封装。
/*
* 重用性
* 获取连接
* 资源释放
* */
public class JDBCUtils {
private static final Properties pro=new Properties();
static {
//类加载,执行一次
try {
// InputStream is = DBUtils.class.getResourceAsStream("jdbc.properties");
// PROPERTIES.load(is);//通过流,将配置文件内容加载到properties集合
pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
Class.forName(pro.getProperty("driver"));
} catch (ClassNotFoundException | IOException e) {
e.printStackTrace();
}
}
//1.获取连接
public static Connection getConnection(){
Connection con=null;
try {
con= DriverManager.getConnection(pro.getProperty("url"),pro.getProperty("username"),pro.getProperty("password"));
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
//2.释放资源
public static void closeAll(ResultSet resultSet, Statement statement,Connection connection){
try {
if (resultSet!=null){
resultSet.close();
}
if (statement!=null){
statement.close();
}
if (connection!=null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}