我们在读取jdbc链接时,通常将链接信息写死在java文件中,或者从数据库链接池中读取。其实还有另外一种方法,将数据库链接信息写到properties文件中。这样做的好处是如果将来需要更换数据库,只需要修改properties文件,并且不需要重新编译即可执行。
例如有一数据库配置文件db.properties。其中的内容如下:
DBDriver=com.mysql.jdbc.Driver
Connection=jdbc:mysql://127.0.0.1:3306/user
User=root
Password=root
建立一个单例模式的类,用于获得数据库链接。
public class DBConnection {
private static DBConnection instance;
public static synchronized Connection getConnection() throws Exception{
if(instance==null){
instance=new DBConnection();
}
return instance._getConnection();
}
private DBConnection() {
}
public Connection _getConnection() throws Exception {
String sDBDriver=null;
String sConnection=null;
String sUser=null;
String sPassword=null;
Properties p=new Properties();
//db.properties放在cn.com.showd.struts包中
InputStream is=getClass().getResourceAsStream("/cn/com/showd/struts/db.properties");
p.load(is);
sDBDriver=p.getProperty("DBDriver");
sConnection=p.getProperty("Connection");
sUser=p.getProperty("User");
sPassword=p.getProperty("Password");
Properties pr=new Properties();
pr.put("user", sUser);
pr.put("password", sPassword);
pr.put("characterEncoding", "UTF-8");
pr.put("useUnicode","true");
Class.forName(sDBDriver).newInstance();
return DriverManager.getConnection(sConnection,pr);
}
}
这样我们就可以通过 _getConnection() 方法去得到一个connection了。