0%

200817 TIL

JDBC(Java Database Connectivity)

  • JDBC(Java Database Connectivity)의 정의

    • JAVA를 이용한 Database접속과 SQL문장의 실행, 그리고 실행 결과로 얻어진 데이터의 핸들링을
      제공하는 방법과 절차에 관한 규약

    • JAVA program 내에서 SQL문을 실행하기 위한 JAVA API

    • SQL과 programming 언어의 통합 접근 중 한 형태

  • JAVA는 표준 interface인 JDBC API를 제공

  • Database는 vendor, 또는 기타 3rd-party에서는 JDBC interface를 구현한
    driver를 제공한다.

JDBC Environmental Setup

  • Install JDK

  • Install JDBC Driver

    • Maven에 아래와 같이 의존성 추가. MySQL사이트에서 다운로드 가능.

      1
      2
      3
      4
      5
      <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.45</version>
      </dependency>

JDBC를 이용한 프로그래밍 방법

  1. import java.sql.*
  2. JDBC 드라이버를 로드한다.
  3. Connection 객체를 생성한다.
  4. Statement 객체를 생성 및 질의 수행
  5. SQL문에 결과물이 있다면 ResultSet 객체를 생성한다.
  6. 모든 객체를 닫는다.

JDBC 클래스의 생성 관계

DriverManager -> Connection -> Statement -> ResultSet

  • DriverManager를 이용해서 Connection인스턴스를 얻는다.
  • Connection을 통해서 Statement를 얻는다.
  • Statement를 이용해 ResultSet을 얻는다.

JDBC 단계별 사용

  1. Import
1
import java.sql.*;
  1. Driver 로드
1
Class.forName("com.mysql.jdbc.Driver");
  1. Connection 얻기
1
2
3
String dburl = "jdbc:mysql://localhost/dbname";

Connection con = DriverManager.getConnection(dburl, ID, PWD);
  • 1, 2, 3까지의 코드 예제

    1
    2
    3
    4
    5
    6
    7
    8
    9
    public static Connection getConnection() throws Exception{
    String url = "jdbc:oracle:thin:@117.16.46.111:1521:xe";
    String user = "smu";
    String password = "smu";
    Connection conn = null;
    Class.forName("oracle.jdbc.driver.OracleDriver");
    conn = DriverManager.getConnection(url, user, password);
    return conn;
    }
  1. Statement 생성
1
2
3
4
5
Statement stmt = con.createStatement();

stmt.execute(“query”); //any SQL
stmt.executeQuery(“query”); //SELECT
stmt.executeUpdate(“query”); //INSERT, UPDATE, DELETE
  1. ResultSet으로 결과 받기
1
2
3
ResultSet rs = stmt.executeQuery("select no from user");
while (rs.next())
System.out.println(rs.getInt("no"));
  1. Close
1
2
3
4
5
rs.Close();

stmt.close();

con.close();
  • example 1

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    public List<GuestBookVO> getGuestBookList(){
    List<GuestBookVO> list = new ArrayList<>();
    GuestBookVO vo = null;
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try{
    conn = DBUtil.getConnection();
    String sql = "select * from guestbook";
    ps = conn.prepareStatement(sql);
    rs = ps.executeQuery();
    while(rs.next()){
    vo = new GuestBookVO();
    vo.setNo(rs.getInt(1));
    vo.setId(rs.getString(2));
    vo.setTitle(rs.getString(3));
    vo.setConetnt(rs.getString(4));
    vo.setRegDate(rs.getString(5));
    list.add(vo);
    }
    }catch(Exception e){
    e.printStackTrace();
    }finally {
    DBUtil.close(conn, ps, rs);
    }
    return list;
    }
  • example 2

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    public int addGuestBook(GuestBookVO vo){
    int result = 0;
    Connection conn = null;
    PreparedStatement ps = null;

    try{
    conn = DBUtil.getConnection();
    String sql = "insert into guestbook values("
    + "guestbook_seq.nextval,?,?,?,sysdate)";
    ps = conn.prepareStatement(sql);
    ps.setString(1, vo.getId());
    ps.setString(2, vo.getTitle());
    ps.setString(3, vo.getConetnt());
    result = ps.executeUpdate();
    }catch(Exception e){
    e.printStackTrace();
    }finally {
    DBUtil.close(conn, ps);
    }

    return result;
    }
  • example 3

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public static void close(Connection conn, PreparedStatement ps){
    if (ps != null) {
    try {
    ps.close();
    } catch (SQLException e) {e.printStackTrace(); }
    }
    if (conn != null) {
    try {
    conn.close();
    } catch (SQLException e) {e.printStackTrace();}
    }
    }