packagecom.demo.day13.jdbc_utils;
importjava.io.FileReader;
importjava.io.IOException;
importjava.net.URL;
importjava.net.URLDecoder;
importjava.sql.*;
importjava.util.Properties;
public classJdbcUtils {
//解决JDBC代码重复度太高---将几个固定的功能 抽取封装到 几个函数中
// 1、为了简便用户操作
// 2、具有通用性
private staticString url1 = null;
private staticString password = null;
private staticString user = null;
private staticString driver = null;
public static void main(String[] args) {
JdbcUtils jdbcUtils = new JdbcUtils();
jdbcUtils.getConnection();
}
//文件的读取,只需要读取一次即可拿到这些值。使用静态代码块
static{
//1.创建Properties集合类。
Properties pro = new Properties();
try{
//就可以动态获取我src目录下"jdbc.properties"的绝对路径了
//获取src路径下的文件的方式--->ClassLoader类加载器
ClassLoader classLoader = JdbcUtils.class.getClassLoader();
URL resour = classLoader.getResource("jdbc.properties");
String path = resour.getPath();
path = URLDecoder.decode(path,"utf-8");
//2.加载文件
pro.load(new FileReader(path));
} catch(IOException e) {
e.printStackTrace();
}
//3.获取数据,赋值
url1 = pro.getProperty("url");
password = pro.getProperty("password");
user = pro.getProperty("username");
driver = pro.getProperty("driver");
try{
//4.注册驱动
Class.forName(driver);
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
}
// Class.forName()
// getConnection
/**
*获取连接
* @return连接对象
*/
public staticConnection getConnection() {
// return DriverManager.getConnection("jdbc:mysql://localhost:3308/day4?serverTimezone=UTC","root","root");
try{
returnDriverManager.getConnection(url1, user, password);
} catch(SQLException throwables) {
throwables.printStackTrace();
return null;
}
}
// execute.Update == > conn,stat
// executeQuery == ? conn,stat,ResultSet rs
/**
*释放资源
* @param stat
* @param conn
*/
public static void close(Connection conn, Statement stat){
if(stat != null){
try{
stat.close();
} catch(SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try{
conn.close();
} catch(SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(Connection conn, Statement stat,ResultSet rs){
if(rs != null){
try{
rs.close();
} catch(SQLException throwables) {
throwables.printStackTrace();
}
}
if(stat != null){
try{
stat.close();
} catch(SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try{
conn.close();
} catch(SQLException throwables) {
throwables.printStackTrace();
}
}
}
}