kujhg 发表于 2015-3-11 08:48:22

eclipse中从配置文件读取数据库配置方法

                      假如配置文件为DBLINK.properties,在项目的根目录的conf文件夹下,
配置文件内容如下:

1
2
3
jdbcUrl=jdbc:orcale:thin:@172.16.5.22:1521:XXDB(数据库名称)
user=xxxx(用户名)
password=xxxx(密码)




然后在你的数据库连接类中读取该配置文件,可以放在加载驱动之前进行读取,
如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
static {
    InputStream in = DBLinkDao.class.getClassLoader().getResourceAsStream("/conf/DBLINK.properties");
(在这行代码中,DBLinkDao是控制搜索配置文件范围,如果后面的路径是绝对路径,则这个类可以是任意的JAVA类,.class.getClassLoader()是为了获得一个类加载器)
    Properties properties = new Properties();
    try{
      properties.load(in);(加载文件)            
    } catch (IOException e1) {
      e1.printStackTrace();
    }            
    CONN_STR = properties.getProperty("jdbcUrl");
    DB_USER = properties.getProperty("user");
    DB_PWD = properties.getProperty("password");
    .....(加载驱动代码)   
}




之后就正常的数据库连接操作
                   

页: [1]
查看完整版本: eclipse中从配置文件读取数据库配置方法