Java - JDBC API (Oracle)

Luna·2023년 1월 13일
0

JAVA

목록 보기
17/32

SQL

  • Structured Query language, 데이터베이스 제어 언어
  1. DML : Date Manipulation Language
    : INSERTC, SELECT, UPDATE, DELETE
  2. DDL : Date Definnition Language
    : CREATE, DROP, ALTER
  3. DCL : Data Control Language
    : COMMIT, ROLLBACK

JDBC API

Java Database Connectivity의 약자로 자바 언어로 데이터베이스 프로그래밍을 하기 위한 라이브러리이다. JDBC는 DBMS에 종속되지 않는 관련 API를 제공하기 때문에 데이터베이스가 어떤 종류인지는 상관 없다. JDBC 드라이버는 각 DBMS 회사에서 제공하는 라이브러리 압축 파일이다. 실습을 할 때는 Oracle 11g xe를 사용했기 때문에 Oracle용 JDBC 드라이버가 필요했다.

JDBC API 클래스

이미지 출처 [Java] JDBC를 사용한 데이터베이스 연동(Mysql)

전체적인 구조는 위와 같고 실제 프로젝트를 할 땐는 Statement 대신 Preparedstatement를 사용했다.

  • StatementPreparedStatement 가장 큰 차이점은 캐시(cache)사용 여부이다. Statement를 사용하면 매번 쿼리를 수행 할 때마다 1~3단계를 거치게 되지만 PreparedStatement는 처음 한 번만 세단계를 거친 후에 캐시에 담아 재사용을 한다. 만약에 동일한 쿼리를 반복적으로 수행한다면 PreparedStatement가 DB에 훨씬 적은 부하를 주며 성능도 좋다.
  • MySQL같은 경우는 두 개의 성능 차이가 거의 나지 않는다고 한다. 그리고 무조건 PreparedStatement가 좋은 건 아니고 Dynamic SQL을 사용할 경우네느 매번 조건절이 달라지므로 굳이 캐싱 할 필요가 없어서statement가 낫다고 한다.

JDBC를 이용한 데이터베이스 연동 과정

Package Import

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

Package 설명

  • Connection : A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection. A Connection object's database is able to provide information describing its tables, its supported SQL grammar, its stored procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData method.

  • DriverManager : The basic service for managing a set of JDBC drivers. As part of its initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property. This allows a user to customize the JDBC Drivers used by their applications.

  • PreparedStatement : An object that represents a precompiled SQL statement. A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

  • ResultSet : A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
    A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.

  • SQLException : An exception that provides information on a database access error or other errors.

출처 Java™ Platform, Standard Edition 8 API Specification

JDBC 드라이버 Load

Connection 객체 생성

PreparedStatement 객체 생성

Query 수행

Result 객체로부터 데이터 추출

객체 Close

0개의 댓글