数据库连接模板
数据库连接模板,通过读取properties文件中的数据库连接信息,连接数据库,通过JDBCConnector获取连接,具体实现如下:
JDBCConfig.java从同路径下的jdbc.properties
文件中读取配置
public class JDBCConfig {
public String getUrl(){
return this.getProperty("url");
}
public String getDriverClassName(){
return this.getProperty("driver_class");
}
public String getUserName(){
return this.getProperty("username");
}
public String getPassword(){
return this.getProperty("password");
}
private String getProperty(String property){
String resources="jdbc.properties";
InputStream inputStream=this.getClass().getResourceAsStream(resources);
Properties properties=new Properties();
try {
properties.load(inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
property=properties.getProperty(property);
return property;
}
}
JDBCConnector.java通过读取的配置获取连接
public class JDBCConnector {
public static Connection getConnection(){
Connection conn=null;
JDBCConfig jc=new JDBCConfig();
String url=jc.getUrl();
String username=jc.getUserName();
String password=jc.getPassword();
try {
Class.forName(jc.getDriverClassName());
conn=DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
}
方法调用:
Connection conn=null;
conn=JDBCConnector.getConnection();