当前位置: 代码迷 >> Java Web开发 >> 小白请问Struts2数据库连接配置有关问题
  详细解决方案

小白请问Struts2数据库连接配置有关问题

热度:2183   发布时间:2013-02-25 21:17:24.0
小白请教Struts2数据库连接配置问题
请问通常在企业开发中,数据库连接串通常放在那个配置文件中或连接池等,及在代码中怎么读取(我用的是Struts2,web.xml?struts.xml?)。非常感谢。
也就是Connection con = DriverManager.getConnection(url, username, password)中url,username,password不在代码中写死;

------解决方案--------------------------------------------------------
呵呵,一般不要写死的话,就要写一个properties问题,把连接数据库参数写在里面,在web.xml中配置,当然,如果使用spring,可以在spring中配置,如果使用hibernate也可以在他里面配置。。。
------解决方案--------------------------------------------------------
==============配置文件中的信息================
driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/databaseName?characterEncoding=utf-8
userName=root
userPwd=mm
=============获取数据库连接的方法==================
//创建数据库连接
protected void openConnection(){
if(conn==null){
InputStream is =getClass().getResourceAsStream("config.properties");
Properties prop= new Properties();
try {
prop.load(is);
String driverName=prop.getProperty("driverName");
String url=prop.getProperty("url");
String userName=prop.getProperty("userName");
String userPwd=prop.getProperty("userPwd");

Class.forName(driverName);
conn=DriverManager.getConnection(url,userName,userPwd);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
  相关解决方案