读取数据库配置文件(配置文件名为dbConfig.properties,放在工程的com包下。),然后获得数据库连接
static String configFile = "com.dbConfig";
private Connection getDbConnection() {
ResourceBundle resource = null;
String driver = null;
String url = null;
String user = null;
String pwd = null;
try{
resource = ResourceBundle.getBundle(configFile); //读取资源文件的类,资源文件配置了数据库连接字符串和连接信息。
driver = resource.getString("driver");
url = resource.getString("url");
user = resource.getString("username");
pwd = resource.getString("pwd");
}catch(Exception ex){System.out.println(ex.getMessage());
return null;
}
Connection conn = null;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url,user,pwd);
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return conn;
}