抽取JDBC工具类:JDBCUTils
*目的:简化书写
*分析:
1、注册驱动
2、抽取一个方法获取连接对象
*需求:传递参数(麻烦),还得保证工具的通用性
配置文件:
url=
user=
password=
3、抽取一个方法释放资源
*代码实现
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
/*文件的读取,只需要读取一次既可以拿到这些值。使用静态代码块
静态只能被静态访问
* */
private static String url;
private static String user;
private static String password;
private static String driver;
static {
//1.properties的使用
try {
Properties pro = new Properties();
ClassLoader classLoader=JDBCUtils.class.getClassLoader();
URL url1 = classLoader.getResource("jdbc.properties");
String path=url1.getPath();
System.out.println(path);
pro.load(new FileReader(path));
//pro.load(new FileReader("E:\\IdeaProjects\\Day01\\day01\\src\\jdbc.properties"));
url = pro.getProperty("url");
user = pro.getProperty("user");
password=pro.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void close(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(ResultSet rs, Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}