Java連接Oracle教學
Context configuration
In a similar manner to the mysql config above, you will need to define your Datasource in your Context. Here we define a Datasource called myoracle using the thin driver to connect as user scott, password tiger to the sid called mysid. (Note: with the thin driver this sid is not the same as the tnsname). The schema used will be the default schema for the user scott.Use of the OCI driver should simply involve a changing thin to oci in the URL string.
| ||||||
web.xml configuration
You should ensure that you respect the element ordering defined by the DTD when you create you applications web.xml file.<resource-ref>
<description>Oracle Datasource example</description>
<res-ref-name>jdbc/myoracle</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
| ||
Code example
You can use the same example application as above (asuming you create the required DB instance, tables etc.) replacing the Datasource code with something likeContext initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();
//etc.
| ||
重點一:建議使用內建的Java 1.4.2版本,而不要去java的網站下載新版本,
由於目前oracle的JDBC最新只有支援到1.4版本,尚未有支援1.5新版的JDBC,
使用1.5.0的可能會出現一些問題。
(一)依不同的版本,了解檔案所在的位置
(1)安裝完整版的oracle ( client + server )
JDBC的位置
C:\oracle\product\10.1.0\Db_1\jdbc\lib\ojdbc14_g.jar
Java 1.4.2的位置
C:\oracle\product\10.1.0\Db_1\jdk\bin\javac.exe
C:\oracle\product\10.1.0\Db_1\jdk\bin\java.exe
(2)安裝client版本的oracle
JDBC的位置
C:\Oracle\product\10.1.0\Client_1\jdbc\lib\ojdbc14_g.jar
Java 1.4.2的位置
C:\Oracle\product\10.1.0\Client_1\jdk\bin\javac.exe
C:\Oracle\product\10.1.0\Client_1\jdk\bin\java.exe
(二)設定classpath與path的環境變數
使用Windows XP作業系統者,在[我的電腦]左側有[檢視系統資訊],
在系統內容的新視窗中,[進階]的分頁下面,有一個[環境變數],
按下去後,又分為上面的[xxx的使用者變數]與下面的[系統變數]。
[xxx的使用者變數],需要設定classpath這個變數,按[新增],
變數名稱 classpath
變數值 .;C:\Oracle\product\10.1.0\Client_1\jdbc\lib\ojdbc14_g.jar
[系統變數],需要設定Path這個變數,在Path這變數上面按[編輯],
變數名稱 Path
變數值 ;C:\Oracle\product\10.1.0\Client_1\jdk\bin\
(以上是以client版本的路徑為例子)
(三)開始寫Java的程式
Java程式能連上Oracle的資料庫,主要是透過JDBC連接的,
而JDBC就是寫在ojdbc14_g.jar這裡面(會依不同版本而不同),
在課程FTP站裡面,有放著助教寫的範例程式,大家可以下載來玩玩,
有 java/debug.java 、 java/test.java 、 java/test2.java
裡面還有一個 java/javadoc.zip 的JDBC說明文件,
大家可以下載解壓縮後看一看,在 javadoc/index.htm 裡面
可以看到 oracle.jdbc 這個class裡面支援的,
有那些 method 可以用的,都寫在裡面!!
重要的程式碼:
Class.forName("oracle.jdbc.driver.OracleDriver");
DriverManage.getConnection("jdbc:oracle:thin:@134.208.27.195:1521:ORCL"
,帳號,密碼);
大家就開始玩玩吧!! 有不懂的地方,大家再互相討論!!
(四)常見的問題 Q&A
(1)確定 java -version 的版本是1.4.2
確定 classpath有設定好,且設定好之後,並無法馬上使用,
必須重新開機之後才能用!!
(2)若發生錯誤為
Exception in thread "main" java.lang.NoClassDefFoundError: xxxx(你取的名字)
問題是出在,你的classpath沒有設定好!!
沒有留言:
張貼留言