工具:eclipse(Myeclipse)
jar包:
commons-collections4-4.0.jar
commons-dbcp-1.4.jar
commons-pool-1.6.jar
Oracle 11g 11.2.0.1.0 JDBC_ojdbc6.jar
<>1.步驟:創建Properties對象
<>2.創建文件路徑
<>3.加載資源配置
<>4.關閉文件路徑
<>5.使用加載資源對象properties調用getProperty()方法
<>6.註冊驅動
2.OverRide (覆蓋,複寫) Connection 中的getConnection方法
將信息返回
3.關閉連接
爲何要使用到配置文件.如果某個公司本來使用是Oracle數據庫,當是,不需要Oracle而是MySQL數據庫
這個時候需要改源代碼.,讓一個不懂代碼的人去改動源碼是非常一件危險的事情,不建議去改動源碼..而是改動配置文件..這樣就能到達通用效果
就像MySQL6.0以上的版本...現在基本是免安裝,,已經不再用傻瓜式安裝..但是MySQL需要配置..這樣就非常方便了,,減少等待時間,直接改動配置文件,,就可以用了
下面的代碼是配置文件代碼:
private static String driver;
private static String url;
private static String username;
private static String password;
//創建配置文件對象
static{
try{
Properties properties = new Properties();
//配置文件路徑
InputStream inStream = JDBCDemo2.class.
getClassLoader().
getResourceAsStream(
"com/csdn/jdbcdemo/date2017_11_12/propertis.txt");
//加載配製文件
properties.load(inStream);
inStream.close();
//獲取配置文件信息
//驅動器
driver = properties.getProperty("driver");
//路徑
url = properties.getProperty("url");
//用戶名
username = properties.getProperty("username");
//密碼
password = properties.getProperty("password");
//註冊驅動器
Class.forName(driver);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(driver);
}
//數據庫連接
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, username, password);
}
//關閉連接
public static void closeConnection(Connection conn){
try {
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
該代碼是測試代碼.查看文件是否配置成功
try {
//連接
Connection connection = JDBCDemo2.getConnection();
//DB對象
Statement state = connection.createStatement();
//SQL語句
String sql = "SELECT * FROM EMP";
//處理結果集
ResultSet rs = state.executeQuery(sql);
//遍歷結果
while(rs.next()){
System.out.println(
rs.getString("ENAME")+" "+
rs.getInt("SAL")+" "+
rs.getInt("DEPTNO")+" "+
rs.getString("EMPNP")
);
}
//關閉連接
rs.close();
state.close();
JDBCDemo2.closeConnection(connection);
} catch (SQLException e) {
e.printStackTrace();
}
時間:2017年11月11日19:21:11寫
修改:
第一次修改:
時間:
2017年11月12日10:25:40
修改:更新一些書寫錯誤