package cn.tedu.jdbc;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils01 {
//final 常亮的初始化,可以在static 静态代码块中进行初始化
public static final String URL;
public static final String USERNAME;
public static final String PASSWORD;
public static final String DRIVER;
private static final Properties prop= new Properties();
//静态代码块,静态初始化器:用于初始化本类的静态成员
static{
try {
//这个prop只能读到文件下下的配置文件,而实际中配置文件会放在src下,所以需要通过类加载器来进行加载
//1,获取ClassLoader对象
ClassLoader loader=JDBCUtils01.class.getClassLoader();
//2,调用ClassLoader的getResource方法
String path=loader.getResource(“config.properties”).getPath();
//3,使用prop读取配置文件的内容
prop.load(new FileInputStream(path));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
URL=prop.getProperty(“url”);
USERNAME=prop.getProperty(“username”);
PASSWORD=prop.getProperty(“password”);
DRIVER=prop.getProperty(“driver”);
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取连接的方法
public static Connection getConnection(){
try {
Connection conn=DriverManager.getConnection(URL, USERNAME, PASSWORD);
return conn;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void close(Connection conn,Statement st,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
rs=null;
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
st=null;
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
conn=null;
}
}
}
}