본문 바로가기

컴퓨터 과학/DB

[DB]JDBC 기초

ODBC(Open DataBase Connectivity)란 데이터베이스에 접근하기 위한 표준 규격이다. api를 통해 다양한 데이터베이스에 접근할 수 있다. 그리고 자바에서 데이터베이스에 접근하기 위해 쓰이는 api를 JDBC(Java Database Connectivity)라 하며, api는 JDBC driver로 구현된다. 이를 통해 자바에서 데이터베이스에 접근할 수 있다.

JDBC는 다음과 같은 과정을 통해 작업이 이루어진다.

  1. jdbc driver를 메모리에 로드
  2. driver manager를 통해 connection 객체를 생성하여 DB에 연결
  3. connection 객체로 prepared statement 객체를 생성하여 sql문 실행

sql문은 2가지 방법으로 실행되며, 각각 다음과 같다.

  1. st.executeUpdate: 결과값이 없는 sql문 실행 (e.g. insert into, delete 등)
  2. st.executeQuery: 결과값이 있는 sql문 실행 (e.g. select 등)

우선 JDBC를 다루기 위해서는 JDBC 라이브러리와 데이터베이스를 다운받아야 한다.

https://dev.mysql.com/downloads/connector/j/

 

MySQL :: Download Connector/J

MySQL Connector/J is the official JDBC driver for MySQL. MySQL Connector/J 8.0 and higher is compatible with all MySQL versions starting with MySQL 5.7. Additionally, MySQL Connector/J 8.0 and higher supports the new X DevAPI for development with MySQL Ser

dev.mysql.com

위 사이트를 통해 JDBC를 다운받자.

이제 프로젝트에 JDBC 라이브러리를 추가하면 된다.

프로젝트 안에서 lib 디렉터리를 우클릭->properties->JDBC를 추가해주면 된다.

 

다음은 JDBC를 통해 Mysql을 다룬 예시이다.

package main;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class Main {
	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		Class.forName("com.mysql.cj.jdbc.Driver");
        String url = "jdbc:mysql://localhost/database";
        Connection con = DriverManager.getConnection(url, "user", "password"); 
        PreparedStatement st = con.prepareStatement(url);
        ResultSet re;

        String sql = "select * from table";
        re = st.executeQuery(sql);
        while (re.next()) {
            int id = re.getInt(1);
            String name = re.getNString(2);
            String number = re.getNString(3);
            Date bir = re.getDate(4);
            System.out.println(id + " " + name + " " + number + " " + bir);
        }

        con.close();
        st.close();
        re.close();
	}
}

위에서 사용된 각 객체들의 의미는 다음과 같다.

DriverManager 객체

jdbc driver를 통해서 connection을 만들어주는 역할을 한다. Class.forName 메서드를 통해 생성된다.

Connection 인터페이스

특정 데이터베이스와의 연결을 의미한다. DriverManager 객체를 통해 생성된다.

Statement 또는 PreparedStatement 인터페이스

sql문을 실행시키고, 결과값을 반환해주는 객체이다. Connection 객체를 통해 생성된다. 결과값이 성공적으로 반환된 경우(e.g. select * from table) ResultSet 객체를 반환한다.

'컴퓨터 과학 > DB' 카테고리의 다른 글

[DB]데이터베이스 기초  (0) 2024.01.14