数据库连接的properties配置文件是怎么连接数据库的

在代码当中的话,关于驱动,url,user和userpasssword都是变化的,最初的代码是如下这样子:

/**
 *@Description:  <br>
 * 〈公共连接数据库的方法〉
 * @Param: []
 * @Return: java.sql.Connection
 * @Author: 
 * @Date: 
 */
public static Connection getConnection() throws SQLException {
    Connection con=null;
    try {
        Class.forName("com.mysql.cj.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    con= DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/student_jpa?serverTimezone=UTC",
            "Kang",
            "qwerty"
    );
    return con;
}

如果说使用一个数据库还好,不用随意改动代码,如果说要使用oracle数据库,这时我们就用到了配置文件jdbc.properties。

在项目resource包下创建jdbc.properties:如下

#属性文件中不要写空行,不要空格
className=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/student_jpa?serverTimezone=UTC
username=Kang
userpassword=qwerty

这时候连接数据库的方法可以这样写:如下

//用属性文件的工具类读取属性文件的内容
private static PropertyUtil pu=new PropertyUtil("jdbc.properties");
private static String className=pu.getValue("className");
private static String url=pu.getValue("url");
private static String username=pu.getValue("username");
private static String userpassword=pu.getValue("userpassword");

/**
 *@Description:  <br>
 * 〈公共连接数据库的方法〉
 * @Param: []
 * @Return: java.sql.Connection
 * @Author: 
 * @Date: 
 */
public static Connection getConnection() throws SQLException {
    Connection con=null;
    try {
        Class.forName(className);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    con= DriverManager.getConnection(url,username,userpassword);
    return con;
}

这样子一来就算换数据库,只要把配置文件当中的相关值换掉就可以啦!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值