import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
/*抽取JDBC工具类 用于获取数据库连接对象Connection 和 使用后释放资源
目的:简化书写
分析:
1、注册驱动也抽取
2、抽取一个方法获取连接对象
需求:不想传递参数,还要保证工具类的通用性
解决:通过配置文件来解决这个问题
配置文件步骤:
新建一个配置文件,此处新建的配置文件例子是jdbc.properties文件
jdbc.properties配置文件中的内容为:
url=
user=
password=
drever=
3、抽取一个方法释放资源
*
* */
//JDBC自定义工具类
public class JDBCUtils {
//获取数据库Connection连接对象
/*//方法一(不建议使用):通过传入三个String分别表示数据库的URL,user,password进入函数getConnection()进行使用
public static Connection getConnection(String url,String user,String password) throws SQLException {//出入三个String分别表示数据库的URL,user,passwo
return DriverManager.getConnection(url,user,password);//调用DriverManager中的getConnection()直接返回一个Connection数据库连接对象
}*/
//方法二
//文件的读取,只需要读取一次即可拿到这些值,使用静态代码块可以满足这个需求
private static String url;
private static String user;
private static String password;
private static String driver;
//读取资源文件,获取值
//1、创建Properties集合类
static{
//加载配置文件
try {
//创建配置文件Properties集合类
Properties properties=new Properties();
//properties.load(new FileReader("C:\\Users\\book\\Desktop\\day20210724\\JDBC学习\\src\\jdbc.properties"));//这里使用绝对路径
//获取src路径下的文件的方式 通过ClassLoader类加载器
ClassLoader classLoader=JDBCUtils.class.getClassLoader();
URL res=classLoader.getResource("jdbc.properties");
String path=res.getPath();
System.out.println(path);
properties.load(new FileReader(path));
//获取配置文件中的数据,赋值给变量
url=properties.getProperty("url");
user=properties.getProperty("user");
password=properties.getProperty("password");
driver=properties.getProperty("driver");
//注册驱动
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取数据库连接对象Connection 其实DriverManager.getConnection(url,user,password);
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
//释放资源 情况一:执行executeUpdate(sql)增删改时 需要释放的资源Connection Statement
public static void close(Connection connection,Statement statement){
if(connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//释放资源 情况二:执行statement.executeQuery(sql)查询时 需要释放的资源Connection Statement ResultSet
public static void close(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();
}
}
}
}
自定义一个JDBC工具类 用于获取数据库连接对象Connection 和 使用后释放资源
最新推荐文章于 2022-05-25 20:37:54 发布