1 / 37

JDBC

JDBC. 컴퓨터정보과 안유정 교수 연구동 410 호 yjahn@mail.mjc.ac.kr. 차례. JDBC 란 ? JDBC 구조 JDBC 접속 JDBC 프로그래밍 예제. JBDC. JDBC (Java Database Connectivity) 자바 환경에서 데이터베이스 처리를 위한 메커니즘 자바 클라이언트와 관계형 데이터베이스 서버와의 연동을 위한 메커니즘 자바 프로그램을 사용하여 데이터베이스에 접속하고 SQL 문을 실행하고 실행 결과로 데이터를 얻는 일련의 과정 제공

melosa
Download Presentation

JDBC

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. JDBC 컴퓨터정보과 안유정 교수 연구동 410호 yjahn@mail.mjc.ac.kr

  2. 차례 • JDBC 란? • JDBC 구조 • JDBC 접속 • JDBC 프로그래밍 예제

  3. JBDC • JDBC (Java Database Connectivity) • 자바 환경에서 데이터베이스 처리를 위한 메커니즘 • 자바 클라이언트와 관계형 데이터베이스 서버와의 연동을 위한 메커니즘 • 자바 프로그램을 사용하여 데이터베이스에 접속하고 SQL문을 실행하고 실행 결과로 데이터를 얻는 일련의 과정 제공 • 자바 프로그램 내에 SQL 명령문을 사용하여 데이터베이스와 연동 • JDBC 구조

  4. JDBC 구조 자바 프로그램 자바 프로그램 JDBC JDBC API JDBC Manager JDBC Driver API JDBC Network Driver JDBC-ODBC Bridge Driver Direct JDBC Driver ODBC Manager & ODBC Driver DBMS DBMS DBMS

  5. JDBC 구조 • JDBC API 데이터베이스 연동을 가능하게 하는, Java.sql 패키지에 들어있는 프로그램들 • JDBC Manager(관리자) • 응용 프로그램이 요구하는 데이터베이스에 접근하도록 적절한 드라이버 선택 • 데이터베이스와 연결 • JDBC Driver 다양한 DBMS 제조사들이 자기 회사의 DB를 Sun사의 자바 프로그램과 연동 할 수 있도록 지원하는 기술로서, 제조사마다 다른 JDBC 드라이버를 제공 MSSQL2K , ORACLE, Cybase, DB2, MySQL 등 다양한 드라이버

  6. JDBC 접속 • 데이터베이스 등록 • 데이터베이스를 만든다. (예 : student.mdb) • 제어판 – 관리도구 – 데이터 원본 (ODBC) – 시스템 DSN 에서 데이터베이스 파일(student.mdb) 추가 • JDBC Driver를 다운로드 • 사용하고자 하는 DBMS 사의 드라이버를 다운로드한다. • JDBC-ODBC Bridge 드라이버를 사용할 경우 SDK에 기본적으로 포함되어 있으므로 별도의 다운로드가 필요없다.

  7. JDBC 접속 • JDBC 드라이버 로딩 • 자바 소스 프로그램 내에, 사용할 JDBC 드라이버를 로드한다. • Class.forName(“드라이버 클래스 명”); • 예 ) Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); Class.forName(“oracle.jdbc.odbc.OracleDriver”); • JDBC 연결 • Java.sql.DriverManager 클래스에 의해 Connection 객체를 생성하여 DB와 연결 • Connection con = DriverManager.getConnection( “JDBC URL” ); • JDBC URL의 형태jdbc : <하위 프로토콜 명> : <데이터베이스 원본> Connection con = DriverManager.getConnection(“jdbc:odbc:student”); Connection con = DriverManager.getConnection( “jdbc:oracle:thin@www.dbserver.co.kr:8080:student” );

  8. JDBC 프로그래밍 • 테이블 생성 예제 학생의 학번, 주민번호, 성별, 핸드폰 필드를 갖는 테이블 생성 예제

  9. JDBC 프로그래밍 • CreateTable.java import java.sql.*; public class CreateTable { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // JDBC 드라이버 로딩 System.err.println("JDBC-ODBC 드라이버를 정상적으로 로드함"); } catch(java.lang.ClassNotFoundException e) { System.err.println("드라이버 로드에 실패했습니다."); }

  10. CreateTable.java (계속) try { Connection con = DriverManager.getConnection("jdbc:odbc:student"); //DB연결 Statement dbSt = con.createStatement(); // Statement 객체 생성 System.out.println("JDBC 드라이버가 정상적으로 연결되었습니다."); String strSql = "CREATE TABLE student_info (학번 long, 주민번호 varchar, 성별 varchar, 핸드폰 varchar)"; // SQL 질의어 생성 dbSt.executeUpdate(strSql); // SQL 질의어 실행 System.out.println("테이블을 생성했습니다."); dbSt.close(); // Statement 객체 종료 con.close(); // DB 연결 해제 } catch (SQLException e) { System.out.println("SQLException : "+e.getMessage()); } } }

  11. JDBC 프로그래밍 • 테이블 생성 예제 결과

  12. JDBC 프로그래밍 • 데이터 삽입 예제 앞에서 생성한 테이블에 학생들의 데이터를 삽입하는 예제

  13. JDBC 프로그래밍 import java.sql.*; public class InsertData { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.err.println("JDBC-ODBC 드라이버를 정상적으로 로드함"); } catch(java.lang.ClassNotFoundException e) { System.err.println("드라이버 로드에 실패했습니다."); } • InsertData.java

  14. InsertData.java (계속) try { Connection con = DriverManager.getConnection("jdbc:odbc:student"); Statement dbSt = con.createStatement(); System.out.println("JDBC 드라이버가 정상적으로 연결되었습니다."); String strSql = "INSERT INTO student_info (학번, 주민번호, 성별, 핸드폰) VALUES (2008081001, ‘891225-1234567', '남', '010-123-1234')"; dbSt.executeUpdate(strSql); System.out.println("데이터 삽입 완료"); dbSt.close(); con.close(); } catch (SQLException e) { System.out.println("SQLException : "+e.getMessage()); } } }

  15. JDBC 프로그래밍 • 데이터 삽입 예제 결과

  16. JDBC 프로그래밍 • 데이터 삽입후 데이터베이스

  17. JDBC 프로그래밍 • 데이터 수정 예제 앞 예제의 테이블에서 학번 = 2008081001 인 학생의 데이터를 수정하는 예제

  18. JDBC 프로그래밍 import java.sql.*; public class UpdateData { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // System.err.println("JDBC-ODBC 드라이버를 정상적으로 로드함"); } catch(java.lang.ClassNotFoundException e) { System.err.println("드라이버 로드에 실패했습니다."); } • UpdateData.java

  19. UpdateData.java (계속) try { Connection con = DriverManager.getConnection("jdbc:odbc:student"); Statement dbSt = con.createStatement(); System.out.println("JDBC 드라이버가 정상적으로 연결되었습니다."); String strSql = "UPDATE student_info SET 주민번호 = ‘880101-1234567', 핸드폰 = '010-123-1234‘ WHERE 학번 = 2008081001"; dbSt.executeUpdate(strSql); System.out.println("데이터 수정 완료"); dbSt.close(); con.close(); } catch (SQLException e) { System.out.println("SQLException : "+e.getMessage()); } // catch 문 } // main } // 프로그램 종료

  20. JDBC 프로그래밍 • 데이터 수정후 데이터베이스

  21. JDBC 프로그래밍 • 데이터 수정 예제 앞 예제의 테이블에서 학번 = 2008081004 인 학생의 데이터를 삭제하는 예제

  22. JDBC 프로그래밍 import java.sql.*; public class DeleteData { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // System.err.println("JDBC-ODBC 드라이버를 정상적으로 로드함"); } catch(java.lang.ClassNotFoundException e) { System.err.println("드라이버 로드에 실패했습니다."); } • DeleteData.java

  23. DeleteData.java (계속) try { Connection con = DriverManager.getConnection("jdbc:odbc:student"); Statement dbSt = con.createStatement(); System.out.println("JDBC 드라이버가 정상적으로 연결되었습니다."); String strSql = "DELETE FROM student_info WHERE 학번 = 2008081004"; dbSt.executeUpdate(strSql); System.out.println("데이터 삭제 완료"); dbSt.close(); con.close(); } catch (SQLException e) { System.out.println("SQLException : "+e.getMessage()); } // catch 문 } // main } // 프로그램 종료

  24. JDBC 프로그래밍 • GUI 를 통한 데이터 삽입 예제

  25. JDBC 프로그래밍 import java.sql.*; import java.awt.*; import java.awt.event.*; public class InsertDataFromGUI extends Frame implements ActionListener{ TextField hakbun, no, male, tel; Button ok, cancel; public InsertDataFromGUI(String title) { super(title); setLayout(new GridLayout(5,1)); • InsertDataFromGUI.java

  26. InsertDataFromGUI.java (계속) Panel top = new Panel(); // 화면을 5개의 판넬로 구성 top.setLayout(new FlowLayout(FlowLayout.LEFT)); Panel middle1 = new Panel(); middle1.setLayout(new FlowLayout(FlowLayout.LEFT)); Panel middle2 = new Panel(); middle2.setLayout(new FlowLayout(FlowLayout.LEFT)); Panel middle3 = new Panel(); middle3.setLayout(new FlowLayout(FlowLayout.LEFT)); Panel bottom = new Panel(); bottom.setLayout(new FlowLayout(FlowLayout.LEFT)); hakbun = new TextField("", 10); no = new TextField("", 14); male = new TextField("", 4); tel = new TextField("", 13); ok = new Button("확인"); cancel = new Button("취소");

  27. InsertDataFromGUI.java (계속) ok.addActionListener(this); cancel.addActionListener(this); top.add(new Label("학번")); top.add(hakbun); middle1.add(new Label("주민번호")); middle1.add(no); middle2.add(new Label("성별")); middle2.add(male); middle3.add(new Label("휴대폰")); middle3.add(tel); bottom.add(ok); bottom.add(cancel); add(top); add(middle1); add(middle2); add(middle3); add(bottom); } // 생성자 끝

  28. InsertDataFromGUI.java (계속) public void actionPerformed(ActionEvent ae) { String t_hakbun, t_no, t_male, t_tel; String s = ae.getActionCommand(); if (s.equals("취소")) { hakbun.setText(""); no.setText(""); male.setText(""); tel.setText(""); } else { // 입력된 데이터를 DB에 저장하기 t_hakbun = hakbun.getText(); t_no = no.getText(); t_male = male.getText(); t_tel = tel.getText();

  29. InsertDataFromGUI.java (계속) // else 블록이 계속됨 try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(java.lang.ClassNotFoundException e) { System.err.println("드라이버 로드에 실패했습니다."); } try { Connection con = DriverManager.getConnection("jdbc:odbc:student"); Statement dbSt = con.createStatement(); String strSql = "INSERT INTO student_info (학번, 주민번호, 성별, 핸드폰) VALUES" +"("+t_hakbun+", '"+t_no+"', '"+t_male+"','"+t_tel+"')"; dbSt.executeUpdate(strSql); System.out.println("데이터 삽입 완료"); dbSt.close(); con.close(); }

  30. InsertDataFromGUI.java (계속) catch (SQLException e) { System.out.println("SQLException : "+e.getMessage()); } } // else } // actionPerformed 끝 public static void main(String[] args) { InsertDataFromGUI win = new InsertDataFromGUI("회원관리"); win.setSize(300, 200); win.setVisible(true); } // main } // 끝

  31. JDBC 프로그래밍 • GUI 를 통한 데이터 삽입, 조회 예제

  32. JDBC 프로그래밍 import java.sql.*; import java.awt.*; import java.awt.event.*; public class ReadDataFromGUI extends Frame implements ActionListener{ TextField hakbun, no, male, tel; Button ok, query, cancel; public ReadDataFromGUI(String title) { super(title); setLayout(new GridLayout(5,1)); • ReadDataFromGUI.java

  33. ReadDataFromGUI.java (계속) Panel top = new Panel(); // 화면을 5개의 판넬로 구성 top.setLayout(new FlowLayout(FlowLayout.LEFT)); Panel middle1 = new Panel(); middle1.setLayout(new FlowLayout(FlowLayout.LEFT)); Panel middle2 = new Panel(); middle2.setLayout(new FlowLayout(FlowLayout.LEFT)); Panel middle3 = new Panel(); middle3.setLayout(new FlowLayout(FlowLayout.LEFT)); Panel bottom = new Panel(); bottom.setLayout(new FlowLayout(FlowLayout.LEFT)); hakbun = new TextField("", 10); no = new TextField("", 14); male = new TextField("", 4); tel = new TextField("", 13); ok = new Button("확인"); query = new Button("조회"); cancel = new Button("취소");

  34. ReadDataFromGUI.java (계속) ok.addActionListener(this); query.addActionListener(this); cancel.addActionListener(this); top.add(new Label("학번")); top.add(hakbun); middle1.add(new Label("주민번호")); middle1.add(no); middle2.add(new Label("성별")); middle2.add(male); middle3.add(new Label("휴대폰")); middle3.add(tel); bottom.add(ok); bottom.add(query); bottom.add(cancel); add(top); add(middle1); add(middle2); add(middle3); add(bottom); }

  35. ReadDataFromGUI.java (계속) public void actionPerformed(ActionEvent ae) { String t_hakbun, t_no, t_male, t_tel; String strSql; String s = ae.getActionCommand(); if (s.equals("취소")) { // 취소버튼이 선택된 경우 hakbun.setText(""); no.setText(""); male.setText(""); tel.setText(""); } else { // 저장이나 조회 버튼이 선택된 경우 try { // JDBC Driver 로드 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch(java.lang.ClassNotFoundException e) { System.err.println("드라이버 로드에 실패했습니다."); } try { // 데이터베이스에 연결 Connection con = DriverManager.getConnection("jdbc:odbc:student"); Statement dbSt = con.createStatement();

  36. ReadDataFromGUI.java (계속) if (s.equals("확인")) { //화면에 입력된 내용을 DB에 저장하기 t_hakbun = hakbun.getText(); t_no = no.getText(); t_male = male.getText(); t_tel = tel.getText(); strSql = "INSERT INTO student_info (학번, 주민번호, 성별, 핸드폰) VALUES" +"("+t_hakbun+", '"+t_no+"', '"+t_male+"','"+t_tel+"')"; dbSt.executeUpdate(strSql); System.out.println("데이터 삽입 완료"); } else { // 조회버튼-화면에 입력된 학번을 DB에서 찾아 학생정보를 화면에 출력하기 long key_hakbun = Integer.parseInt(hakbun.getText()); // 화면에 입력된 학번을 문자열에서 long 으로 형변환하여 key_hakbun에 저장 strSql = "SELECT * FROM student_info WHERE 학번 ="+ key_hakbun; ResultSet result = dbSt.executeQuery(strSql); while (result.next()) { no.setText(result.getString("주민번호")); male.setText(result.getString("성별")); tel.setText(result.getString("핸드폰")); } // while 끝 } // else - 조회 버튼이 선택된 경우

  37. ReadDataFromGUI.java (계속) dbSt.close(); con.close(); } catch (SQLException e) { System.out.println("SQLException : "+e.getMessage()); } } // else - 저장이나 조회 버튼이 선택된 경우 } // actionPerformed 끝 public static void main(String[] args) { ReadDataFromGUI win = new ReadDataFromGUI("회원관리"); win.setSize(300, 200); win.setVisible(true); } // main } // 프로그램 종료

More Related