日期:2014-05-16  浏览次数:20438 次

重构JDBC连接方式

一个项目有几个库,每次部署都要在内部好几个配置中更改连接太麻烦

把JDBC写在项目外面即增强的项目的灵活性,又方便了自身的使用

?

用 .properties文件 properties文件作用如把JDBC连接配置写在其中

然后在连接时读取properties文件里的连接配置在代码中使用JDK提供Properties类一个单例模式

private static Properties prop = new Properties();

?

public static Properties getConfigureProperties(){

return prop;

}

static{

try{

InputStream in = SqlUtil.class.getClassLoader().getResourceAsStream("sqldb.properties");

? ?prop = new Properties();

? ?

prop.load(in);

?

String driver = prop.getProperty("db.driver");

Class.forName(driver);

url = prop.getProperty("db.url");

username = prop.getProperty("db.username");

password = prop.getProperty("db.password");

?

}catch (Exception e) {

?

e.printStackTrace();

}

}

?

Properties?外部文件中

db.driver=com.microsoft.jdbc.sqlserver.SQLServerDriver

db.url=jdbc:microsoft:sqlserver://127.0.0.1:1434;DatabaseName=CertificateMSG1215;selectMethod=cursor

db.username=sa

db.password=tcaccp

?

这样要改连接配置只需在外部更改无需再代码里更改避免了硬编码的局限性。其他类似的文件原理相同