读取JDBC配置文件的二种方式

一 读取jdbc.properties文件

1  新建jdbc.properties文件,如下:

jdbc.user=root
jdbc.password=123456
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/database?useUnicode=true&characterEncoding=utf8

2 编写readPro()方法如下:

private static void readPro() {
        Properties pro=new Properties();
        InputStream in = PropertiesTest.class.getClassLoader().getResourceAsStream("JDBC.properties");
        try {
            pro.load(in);//加载properties配置文件
            String user = pro.getProperty("jdbc.user");
            String password = pro.getProperty("jdbc.password");
            String url = pro.getProperty("jdbc.url");
            String driver = pro.getProperty("jdbc.driver");
            System.out.println(user);
            System.out.println(password);
            System.out.println(url);
            System.out.println(driver);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

3 编写测试类PropertiesTest,调用readPro方法,如下:

public class PropertiesTest {
    public static void main(String[] args) {
        readPro();//读取jdbc.properties配置文件
        
    }
}

 

二 读取jdbc.xml文件

1  新建jdbc.xml文件,如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>jdbc</comment>
    <entry key="jdbc.user">root</entry>
    <entry key="jdbc.password">123456</entry>
    <entry key="jdbc.driver">com.mysql.cj.jdbc.Driver</entry>
    <entry key="jdbc.url">jdbc:mysql://xxx.xxx.xxx.xxx:3306/database?useUnicode=true&amp;characterEncoding=utf8</entry>
</properties>

2 编写readXml()方法如下:

private static void readPro() {
        Properties pro=new Properties();
        InputStream in = PropertiesTest.class.getClassLoader().getResourceAsStream("JDBC.properties");
        try {
            pro.load(in);//加载properties配置文件
            String user = pro.getProperty("jdbc.user");
            String password = pro.getProperty("jdbc.password");
            String url = pro.getProperty("jdbc.url");
            String driver = pro.getProperty("jdbc.driver");
            System.out.println(user);
            System.out.println(password);
            System.out.println(url);
            System.out.println(driver);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

 

3 编写测试类PropertiesTest,调用readXml方法,如下:

public class PropertiesTest {
    public static void main(String[] args) {
        readPro();//读取jdbc.properties配置文件
        
    }
}
posted @ 2020-01-20 16:16  自信的咸鱼  阅读(3290)  评论(0编辑  收藏  举报