package com.wpcweb.bank.utils;
import javax.management.remote.rmi._RMIConnection_Stub;
import java.sql.*;
import java.util.ResourceBundle;
/**
* @author 一介草莽子
* version 1.0
*/
@SuppressWarnings({"all"})
//JDBC工具类
public class DBUtils {
//获得配置文件里的数据
private static ResourceBundle Bundle = ResourceBundle.getBundle("resources/jdbc");
//获得数据
private static String driver = Bundle.getString("driver");
private static String url = Bundle.getString("url");
private static String user = Bundle.getString("user");
private static String password = Bundle.getString("password");
//获得驱动
static {
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//构造器已优化是为了不让别人创建对象因为是工具类全是静态方法
private DBUtils() {
}
//获得连接
public static Connection getConnection() throws SQLException {
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
//关闭连接
public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
1.创建配置文件
2.创建工具类(构造器私有化避免用的人创建对象因为里面全是静态方法用不到创建对象)
3.利用ResourceBundle.getBundle("resources/jdbc");获得配置问价里面的内容
4.获得的驱动 Class.forName(driver);只需要获取一次所以放到静态代码块
5.创建获取连接方法(静态的)
6.创建关闭连接的方法(静态的)
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db02
user=root
password=4653long