日期:2014-05-17 浏览次数:20753 次
public class ConnDB { public Connection conn = null; public Statement stmt = null; public ResultSet rs = null; private static String propFileName = "/connDB.properties"; // 指定资源文件保存的位置 private static Properties prop = new Properties(); // 创建并实例化Properties对象的实例 private static String dbClassName = "";//定义保存数据库驱动的变量 private static String dbUrl = ""; private static String dbUser = ""; private static String dbPwd = ""; //定义构造方法 public ConnDB() { try { //将Properties文件读取到InputStream对象中 InputStream in = getClass().getResourceAsStream(propFileName); prop.load(in); // 通过输入流对象加载Properties文件 dbClassName = prop.getProperty("DB_CLASS_NAME",dbClassName); // 获取数据库驱动 dbUrl = prop.getProperty("DB_URL", dbUrl); //获取URL dbUser = prop.getProperty("DB_USER", dbUser); //获取登录用户 dbPwd = prop.getProperty("DB_PWD", dbPwd); //获取密码 } catch (Exception e) { e.printStackTrace(); } } public Connection getConnection() { System.out.println("前conn="+conn); try { System.out.println("1111111"); Class.forName(dbClassName); conn = DriverManager.getConnection(dbUrl, dbUser, dbPwd); System.out.println("数据库连接成功!"+dbUrl); } catch (Exception ee) { ee.printStackTrace(); } System.out.println("后conn="+conn); if (conn == null) { System.err.println("警告: DbConnectionManager.getConnection() 获得数据库链接失败.\r\n\r\n链接类型:" + dbClassName + "\r\n链接位置:" + dbUrl + "\r\n用户" + dbUser + "\r\n密码"+ dbPwd); } return conn; }