把JDBC工具类中的数据库名,用户名,密码等信息放到properties配置文件中,在配置文件中修改数据库信息不用重启服务器就能修改成功。因为配置文件不需要编译,每次运行类自动加载。
public class JDBCUtils {
//驱动
private static String driverName;
//JDBC链接串
private static String url;
//数据库名字
private static String userName;
//数据库密码
private static String password;
//静态代码块,目的:让第一次使用到JDBCUtils时加载驱动,第二次以后不再加载
static {
try {
//获取配置文件
Properties ps = new Properties();
ps.load(new FileReader("jdbc_config.properties"));
driverName = ps.getProperty("driverName");
url = ps.getProperty("url");
userName = ps.getProperty("userName");
password = ps.getProperty("password");
//1.加载驱动
Class.forName(driverName);
} catch (Exception e) {
throw new RuntimeException("驱动加载失败");
//当驱动加载失败时,让程序直接停止运行
}
}
//获取数据库连接
public static Connection getConnection() throws Exception {
//2.获取数据库的连接对象
Connection connection = DriverManager.getConnection(url,userName,password);
return connection;
}
//关闭所有资源
public static void closeAll(Connection con, Statement st, ResultSet rs) {
if(con != null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(st != null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
配置文件内容: