1 / 42

Java DB Programming

Java DB Programming. 손기락 한국외국어대학교 컴퓨터공학과. JDBC?. JDBC(Java Database Connectivity) Methods and Protocols about Database connection using Java, Execution of SQL statements, Retrieving results sets A set of Java API Integration of SQL and Programming language

sandro
Télécharger la présentation

Java DB Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaDB Programming 손기락 한국외국어대학교 컴퓨터공학과

  2. JDBC? • JDBC(Java Database Connectivity) • Methods and Protocols about Database connection using Java, Execution of SQL statements, Retrieving results sets • A set of Java API • Integration of SQL and Programming language • Standard interface JDBC API for developers and drivers provided by vendors or third-party

  3. Why JDBC? (1) • Developing applications independent of DBMS • Consider the following. What is the problem? Oracle Library Database Oracle Application Sybase Library Database Sybase Application Informix Library Database Informix Application

  4. Why JDBC? (2) • One application uses a single interface to access different DBMS Once compiled, can be executed anywhere by replacing a proper JDBC diver only

  5. JDBC Driver (1) • What driver vendors provide? • Implementation of JDBC API (interface) classes (called drivers) • Real objects of JDBC API programmers use are the objects provided by vendors (Polymorphism) • DriverManager class gets DB connection using JDBC drivers

  6. JDBC Driver (2) • DriverManager is a class, but other API are interfaces • Need to call a static method

  7. JDBC Structure Java Application JDBC API JDBC Driver Manager JDBC Driver API JDBC-Net Driver JDBC-ODBC Bridge Driver Driver A Driver B JDBC implementation alternatives ODBC and DB Driver JDBC Middleware Protocol Proprietary database access protocols

  8. java.sql package structure (1)

  9. java.sql package structure (2) • JDBC Interfaces • Driver • Connection • Statement • ResultSet • PreparedStatement • CallableStatement • ResultSetMetaData • DatabaseMetaData • Array , Blob, Clob

  10. java.sql package structure (3) • JDBC Classes • DriverManager • Types • DriverPropertyInfo • Date • Time • Timestamp • JDBC Exceptions • SQLException • SQLWarning • DataTruncation

  11. java.sql package • java.sql.DriverManager • Manages drivers and returns a driver connection corresponding to URL • java.sql.Connection • Logical database connection • java.sql.Statement • SQL Statements • java.sql.ResultSet • Result set

  12. 1 Driver Manager Connection Statement ResultSet 4 DatabaseMetaData 2 ResultSetMetaData 3 5 6 Oracle DB Connection using JDBC (1)

  13. any SQL SELECT INSERT, UPDATE, DELETE DB Connection using JDBC (2) • Step 1 : Driver Loading • Class.forName(“driver-name”); • Step 2 : Obtain Connection • Connection con = DriverManager.getConnection(“url”); • Step 3 : Create Statement • Statement stmt = con.createStatement(); • Step 4 : Execute Query • stmt.execute(“query”); • stmt.executeQuery(“query”); • stmt.executeUpdate(“query”);

  14. java.sql.Connection Connection은 데이터베이스에 접근하기 위한 객체를 생성하는 인터페이스이다.

  15. java.sql.Statement Statement는 query문을 실행하고 그것에 대한 결과 값을 가져오기 위해서 사용되는 인터페이스

  16. java.sql.PreparedStatement PreparedStatement는 동일한 query문이 여러 번 반복적으로 수행될 때 주로 사용되는 인터페이스

  17. java.sql.ResultSet ResultSet은 Statement 인터페이스의 executeQuery() 메서드가 반환하는 결과로 얻은 데이터를 저장

  18. Statement의 사용 예 Statement는 query문을 실행하고 그것에 대한 결과 값을 가져오기 위해서 사용되는 인터페이스 Connection con = DriverManager.getConnection(“conection_string",“id","password"); Statement stmt =con.createStatement(); ResultSet rs = stmt.executeQuery("select * from table”);

  19. PrepraredStatement의 사용 예 Statement는 query문을 실행하고 그것에 대한 결과 값을 가져오기 위해서 사용되는 인터페이스 PreparedStatement ps = con.prepareStatement("update member set name = ? where id= ? "); // 앞에는 Prepared, 뒤쪽은 prepare인 것에 주의한다 ps.setString(1,"김철수"); // 첫번재 ? 이 1번이 된다 ps.setString(2,"1"); // 두번째 ?의 값 // setString 말고도, setDate, setArray, setCharacterStream등의 사용이 가능하다. ps.executeUpdate();

  20. CallableStatement CallableStatement stmt = conn.prepareCall("{call myStoredPro(?,?,?)}"); stmt.setInt(1,3); stmt.registerOutParameter(2, java.sql.Types.VARCHAR); stmt.registerOutParameter(3, java.sql.Types.INTEGER); stmt.execute();

  21. ResultSet • executeQuery()를 실행하면 ResultSet 타입의 객체를 반환된다. 이 객체는 실행된 쿼리문의 결과값을 가지고 있는데 ResultSet의 몇 가지 메소드를 이용하면 ResultSet에 저장된 정보를 사용할 수 있다. • ResultSet rs = stmt.executeQuery("SELECT id, name FROM CUSTOMERS"); • 위와 같이 select 쿼리를 실행했다면 하나이상의 row를 지니고 있는데. 현재 row에서 다음 row로 넘기려면 rs.next() 와 같이 사용하면 된다. 각 row가 선택이 되었으면 각 컬럼의 데이터를 불러 오면 되는데, 두 가지 방법이 있다. • ■ 컬럼위치로 검색 • String name=rs.getString(1); // 첫 번째 컬럼인 id가 선택된다 • ■ 컬럼이름으로 검색 • String name=rs.getString("name"); // 컬럼이름이 name인 것이 선택된다 • getString의 String 대신 Int, Double, 등과 같은 자료형을 사용하면 해당 자료형에 맞는 데이터가 리턴된다. (getString(), getInt(), getDouble() 등)

  22. Closing DB Connection • Java는 메모리 관리를 따로 하지 않아도 자체적으로 garbage collection 기능이 있어 사용되지 않는 객체는 자동적으로 처리된다. 그러나, Sun은 JDBC 드라이버와 같이 외부 지원되는 드라이버에 대해서는 생성된 객체를 코드 내에서 소멸시키도록 권장하고 있다. JDBC API는 이를 위해 close() 메소드를 제공하는데, close() 메소드를 사용해야 할 클래스는 Connection, Statement, PreparedStatement, ResultSet 등이다. 따라서, 데이터베이스에 접속하여 SQL 구문을 모두 수행했다면 다음처럼 close() 메소드를 사용하여 객체를 모두 소멸시키도록 한다. • rs.close(); // 결과값 객체 소멸 • stmt.close(); // SQL문 객체 소멸 • conn.close(); // 연결 객체 소멸 • Connection은 상당한 Overhead를 가져온다. 따라서 최적화된 상태를 유지하기 위해서는 반드시 Connection을 닫아 주어야 한다.

  23. 트랜잭션 관련 메소드

  24. 트랜잭션예제 import java.sql.*; public class TransactionEx{ static{ try{ Class.forName("oracle.jdbc.driver.OracleDriver"); }catch(ClassNotFoundException cnfe){ cnfe.printStackTrace(); } } public static void main(String[] args){ Connection conn = null; PreparedStatement pstmt = null; boolean success = false; //success 변수는 정상적으로 수행되는 경우는 true를 저장하고 예외가 발생했을 경우는 false로 설정하여 //커밋과 롤백한다. try{ conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:oracle","scott","tiger"); String sql = "create table test1(id varchar2(10),"+"password varchar2(10))"; pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); conn.setAutoCommit(false); //setAutoCommit(false) 메서드로 트랜잭션을 시작한다. sql = "insert into test1 values('syh1011','1111')"; pstmt = conn.prepareStatement(sql); pstmt.executeUpdate();

  25. 트랜잭션예제 //첫 번째 로우를 삽입한다.정상적으로 수행된다. sql = "insert into test1 values('syh1011','2222')"; pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); //두 번째 로우를 삽입한다.정상적으로 수행된다. sql = "insert into test1 values('syh1011','3333'"; pstmt = conn.prepareStatement(sql); pstmt.executeUpdate(); //SQL문이 잘못되었기 때문에 예외가 발생한다. success = true; } catch(Exception e){ e.printStackTrace(); }finally{ try{ if(success){ conn.commit(); }else{ conn.rollback(); } //정상적으로 수행되었다면 success는 true, 예외가 발생하였다면 false가 저장된다. 이 예제에서는 //예외가 발생했기 때문에 success변수에 false가 저장되었다. 따라서 롤백이 수행되어 모든 작업을 //취소하게 된다. if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); }catch(SQLException sqle){ sqle.printStackTrace(); } } } }

  26. java.sql.SQLException SQLExeception 객체가 제공하는 SQLException 에 대해서 알아보자.

  27. SQLException 예

  28. Programming example using JDBC

  29. Example 1- Printthe last names and salary of an employee given SSN

  30. Example 1

  31. Example 1

  32. Example 2 - Printthe last names and salary of an employee given DNUMBER

  33. Example 2

  34. Example 3 - Find All Supervisees

  35. Example 3

  36. Example 3

  37. Example 3

  38. Example 3

  39. Example 3

  40. Example 3

  41. Example 3

  42. Example 3

More Related