標籤:des style blog io color ar os 使用 java
一:首先是將JDBC的驅動包oracle6.jar複製到Tomcat安裝路徑下的llib目錄下
二:在web工程目錄下的META-INF\context.xml檔案下輸入以下代碼(特別注意檔案夾別搞錯了):
<span style="font-size:14px;color:#663366;"><?xml version="1.0" encoding="UTF-8"?><Context debug="5" reloadable="true"> <WatchedResource>WEB-INF/web.xml</WatchedResource> <Resource name="jdbc/oracle" type="javax.sql.DataSource" auth="Container" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:orcl" username="C##SCOTT" password="tiger" maxActive="5" maxIdle="2" maxWait="6000" /></Context></span>
在myeclipse中沒有context.xml檔案需要自己建立。
三:在web工程目錄下的在WEB-INF\web.xml檔案下配置以下代碼
<span style="color:#009900;"><resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/oracle</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth></resource-ref></span>
四:配置完成後便是測試了
Connection con = null;// 建立一個資料庫連接 Statement stmt = null;// 建立先行編譯語句對象,一般都是用這個而不用Statement ResultSet result = null;// 建立一個結果集對象 try{ Context Ctx = new InitialContext(); Context envCtx = (Context) Ctx.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup("jdbc/oracle"); con = ds.getConnection(); System.out.println("資料庫連接成功!"); stmt = con.createStatement(); String strSql = "select * from usertable2"; result = stmt.executeQuery(strSql); while(result.next()){ out.print(result.getString("username")); } } catch(Exception ex){ out.print("Exception is :"+ex.getMessage()); ex.printStackTrace(); } finally { try { // 逐一將上面的幾個對象關閉,因為不關閉的話會影響效能、並且佔用資源 // 注意關閉的順序,最後使用的最先關閉 result.close(); stmt.close(); con.close(); System.out.println("資料庫連接已關閉!"); } catch (Exception e) { e.printStackTrace(); } }
Oracle串連池操作