package net.cyan.cy01;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JDBCutil {
//使用静态代码块进行流的操作
private static String user;
private static String password;
private static String url;
private static String className;
static{//此代码块仅在类加载时运行一次
FileInputStream fis=null;
try {
Properties properties=new Properties();
//创建读取数据的流
fis =new FileInputStream("jdbc.txt");
//1.3加载流
properties.load(fis);
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
className = properties.getProperty("className");
} catch (FileNotFoundException e) {
//将编译时异常转化为运行异常
throw new RuntimeException(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭流操作
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static Connection getConnection() {
//通过反射获取对象
try {
Class.forName(className);
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
} catch (ClassNotFoundException e) {
//将编译时异常转化为运行异常
throw new RuntimeException(e.getMessage());
}
}
public static void close(PreparedStatement ps, Connection connection) {
if (ps!=null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(PreparedStatement ps, Connection connection, ResultSet resultSet) {
close(ps,connection);
if (resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}