1. 程式人生 > >JDBC連接Oracle

JDBC連接Oracle

數據庫訪問 etc null host while sql語句 creat 步驟 ora

JDBC連接數據庫過程就是:

1,加載驅動,建立連接

2,創建sql語句對象

3,執行sql語句

4,處理結果集

5,關閉連接

這五個步驟中主要了解4大知識點:

1,驅動管理DriverManager

  ClassForName("Oracle.jdbc.driver.OracleDriver")

2,連接對象

  Connection接口 :負責應用程序對數據庫的連接,在加載驅動後,使用url,username,password三個參數創建具體的數據庫連接1

3,sql語句對象接口

  Statement接口用來處理發送到數據庫的SQL語句對象

4,結果集接口

  ResultSet接口:執行查詢SQL語句後返回的結果集合。

public void findAll(){
  Connection con=null;
  Statement stmt=null;
  ResultSet rs=null;
  try {
    Class.forName("oracle.jdbc.OracleDriver");
    con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe";,"username","password");
    stmt=con.createStatement();
    String sql="select empno, ename, sal, hiredate from emp";
    rs=stmt.executeQuery(sql);
    while (rs.next()) {
      System.out.println(rs.getInt("empno") + ","
      + rs.getString("ename") + ","
      + rs.getDouble("sal") + "," + rs.getDate("hiredate"));
    }
  } catch (ClassNotFoundException e) {
    System.out.println("驅動類無法找到!");
    throw new RuntimeException(e);
  } catch (SQLException e) {
    System.out.println("數據庫訪問異常!");
    throw new RuntimeException(e);
  }finally {
    try {
    if (rs != null) {
      rs.close();
    }
    if (stmt != null) {
      stmt.close();
    }
    if (con != null) {
      con.close();
    }
    } catch (SQLException e) {
      System.out.println("關閉連接時發生異常");
    }
  }
}

JDBC連接Oracle