淺談如何利用Java的JDBC操作Oracle數(shù)據(jù)庫
參考 http://java.sun.com/docs/books/tutorial/jdbc/basics/index.html Java JDBC中操作Oracle數(shù)據(jù)庫,經(jīng)過以下幾個步驟,
1.將OracleHome/jdbc/lib/目錄的所有文件添加到j(luò)re/lib/ext目錄;(配置Java JDBC驅(qū)動)
2.創(chuàng)建odbc源,在控制面板=》管理工具=》數(shù)據(jù)源(odbc)中添加DSN,比如取名為OracleDSN,選擇一個Service,輸入用戶名密碼,測試連接,若通過說明成功;
3.在程序中加載jdbc驅(qū)動(下面的例子用的是JdbcOdbc驅(qū)動),建立連接,執(zhí)行Query.
下面是連接OracleDSN ODBC data source的一個類,方法Test()連接數(shù)據(jù)庫后,讀取tbljob的內(nèi)容,并顯示所有記錄。
- import java.sql.*;
- class OracleConnect {
- public static void Test() { //connection by JdbcOdbcDriver
- try {
- //load the driver:
- Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
- //connect the Database,OracleDSN is the ODBC data source ;
- String url = "jdbc:odbc:OracleDSN";
- Connection conn = DriverManager.getConnection(url, "system",
- "system_passwd");
- // Create a Statement
- Statement stmt = conn.createStatement();
- // Select first_name and last_name column from the employees table
- ResultSet rset = stmt.executeQuery("select * from tbljob;");
- // Iterate through the result and print the employee names
- while (rset.next())
- System.out.println(rset.getString(1) + " " + rset.getString(2));
- // Close the RseultSet2
- rset.close();
- // Close the Statement
- stmt.close();
- // Close the connection
- conn.close();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
【責(zé)任編輯:彭凡 TEL:(010)68476606】