日期:2014-05-16 浏览次数:20481 次
1:在WEB工程SEC目录下新建一个database.properties文件,里面保存连接数据库信息
2:public class DBUtil {
private String driver;
private String url;
private String user;
private String psw;
private static DBUtil dbutil=null;
private DBUtil() throws IOException, ClassNotFoundException{
InputStream is=this.getClass().getClassLoader().getResourceAsStream("database.properties");
Properties p=new Properties();
p.load(is);
driver=p.getProperty("driver");
url=p.getProperty("url");
user=p.getProperty("user");
psw=p.getProperty("psw");
Class.forName(driver);
}
/**
* 获得数据库帮助类唯一实例
*/
synchronized public static DBUtil getInstance() throws IOException, ClassNotFoundException{
if(dbutil==null){
dbutil=new DBUtil();
}
return dbutil;
}
/**
* 获取数据库连接 无参数
*/
synchronized public Connection getConnection() throws SQLException{
return DriverManager.getConnection(url,user,psw);
}