通过properties文件连接数据库
1.简介
通过properties写数据库的配置,以后换数据库配置只要改properties文件,当然以后配置我直接从这CV了,争做合格的cv工程师。
2.db.properties文件:
#DBUtil的配置文件 存放的都是键值对的数据 key=value
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/ibox
username=root
password=root
3.DBUtil类 连接数据库的工具类
package com.example.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class DBUtil {
//驱动全类名
private static String driverClassName;
//连接的url
private static String url;
//用户名
private static String username;
//密码
private static String password;
static {
try {
//1.通过类对象获取类加载器
ClassLoader classLoader = DBUtil.class.getClassLoader();
//2.通过输入流读取db.properties文件
InputStream stream = classLoader.getResourceAsStream("db.properties");
//3.创建properties对象
Properties properties = new Properties();
//4.通过properties对象加载文件
properties.load(stream);
//5.用properties通过key拿value
driverClassName = properties.getProperty("driverClassName");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
//6.加载数据库驱动
Class.forName(driverClassName);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取连接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
//通过驱动管理拿到数据库连接返回连接对象
return DriverManager.getConnection(url,username,password);
}
/**
* 关闭连接
*
*/
public static void close(Connection conn, PreparedStatement ps, ResultSet rs){
//如果连接未关闭,则关闭连接
if(rs!=null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}