当我们开发数据库系统的时候,我们要通过jdbc连接数据库,这个时候我们可能会写出这样的类似代码
public class basicconnection {
private string dbdriver;
private string dburl;
private string dbuser;
private string dbpassword;
public static void main(string args[]) {
}
public basicconnection {
init();
}
private void init() {
try {
// set the properties
this.dbdriver = "oracle.jdbc.driver.oracledriver";
this.dburl = "jdbc:oracle:thin:@127.0.0.1:1521:dev2";
this.dbuser = "monkey";
this.dbpassword = "password";
// load the driver
class.forname(dbdriver);
} catch (exception e) {
throw new runtimeexception("unable to init, exiting...");
}
}
private connection getconnection()
throws sqlexception {
return drivermanager.getconnection(dburl, dbuser, dbpassword);
}
}
这样的代码,工作起来没有什么问题。但是他存在的缺点就是dbdriver等属性都是硬编码的,当你的数据库的地址改变,用户名改变的情况下,这个代码就不能正常的工作了。你必须重新编译这个代码。
在java.util包内有一个properties类,他扩展了hashtable。可以用来存储类似于上述情况的数据。你必须要准备一个文本文件,比如config.props,在文件里面写好你要配置的数据。例如
dbdriver=oracle.jdbc.driver.oracledriver
dburl=jdbc:oracle:thin:@127.0.0.1:1521:dev2
dbuser=monkey
dbpassword=password
使用properties类非常的简单,你只需要首先把这个文件转换成inputstream,然后调用properties的成员方法load(inputstream is),这样就把数据设置好了,当我们要读取的时候使用getproperty(string key)就可以了,返回值为string类型。注意properties只能存储string类型的对象。
这样我们就可以提供一个新的方法来读取文件中的数据了,而不是使用硬编码的方式。下面给出改进后的程序
private void init() {
try {
string propsfilename = "config.props";
inputstream is = getclass().getresourceasstream(propsfilename);
properties p = new properties();
p.load(is);
// set the properties
this.dbdriver = p.getproperty("dbdriver");
this.dburl = p.getproperty("dburl");
this.dbuser = p.getproperty("dbuser");
this.dbpassword = p.getproperty("dbpassword");
// load the driver
class.forname(this.dbdriver);
} catch (exception e) {
throw new runtimeexception("unable to initialize, exiting...");
}
}
这样我们只需要修改配置文件就可以了,没有必要再修改源代码。
闽公网安备 35060202000074号