import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.*; import java.util.Properties;
public class DBConnection implements IDBConnection {
public void closeConnection(Connection c) { //判断 connection是否为null
if(null != c ){ try { if(!c.isClosed()){ //如果连接没有关闭
c.close(); } } catch (SQLException e) { e.printStackTrace(); } }
}
public Connection getConnection() { //声明数据库连接
Connection connection = null; try { connection = DriverManager.getConnection(dbURL, userName, userPwd); } catch (SQLException e) { e.printStackTrace(); } return connection; } public DBConnection() { //读取jdbc.properties属性文件
Properties prop = new Properties(); //加载属性文件
//加载驱动程序
try { prop.load(new FileInputStream("D:/Program Files/Apache Software Foundation/Tomcat 5.5/webapps/XXXX/src/jdbc.properties")); //读取属性
userName = prop.getProperty("userName"); dbURL = prop.getProperty("dbURL"); userPwd = prop.getProperty("userPwd"); driverName = prop.getProperty("driverName"); Class.forName(driverName); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private String userName; private String dbURL; private String userPwd; private String driverName; }
|