標籤:資料庫 row run for dal set oid 應用程式 cti
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