標籤:blog http io ar os sp for java on
1.匯入驅動包:
a.找到oracle安裝目錄下的jdbc/lib中的檔案classes12.jar;
b.右擊你建立的JAVA工程,找到Build path,選擇Add External Archives,找到你要匯入的包classes12.jar,點擊開啟就可以引入,引入後在工程下面的ReferencedeLibraries下便能顯示這個包。
2.代碼測試:
import java.sql.*; public class oracle { String driver = "oracle.jdbc.OracleDriver"; String url="jdbc:oracle:thin:@localhost:1521:orcl";//@主機名稱:監聽連接埠:資料庫執行個體名稱,Attention notes:the port is generally 1521 String name = "system";//登入名稱 String pwd = "orcl";//登陸密碼 private static Statement sql = null; private static ResultSet rs = null; private static Connection con = null; public Connection getCon() { try { Class.forName(driver); //註冊oracle資料庫驅動 } catch (ClassNotFoundException e1) { System.out.println("驅動載入失敗!"); e1.printStackTrace(); } try { con = DriverManager.getConnection(url, name, pwd);//擷取連接字串 } catch (SQLException e) { System.out.println("驅動或資料庫連接失敗!"); e.printStackTrace(); } return con; } public static void main(String[] args) { try { oracle db = new oracle(); Connection con = db.getCon(); if (con != null) { System.out.println("資料庫連接成功!"); } else { System.out.println("資料庫連接失敗!"); } sql = con.createStatement(); rs = sql.executeQuery("select * from students"); System.out.println("編號\t學號\t姓名\t性別\t出生日期"); while (rs.next()) { System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getString(4)+"\t"+rs.getString(5)); } } catch(Exception e) { e.printStackTrace(); } } }
3.測試結果:
Java串連Oracle10g