WEB WAS/미들웨어

JDBC 란?

chanstory 2023. 6. 4. 11:27
반응형

JDBC란?

=> Java Database Connectivity

=> 데이터 베이스에 대한 표준화 된 접근 방식 제공

=> DBMS에 독립적으로 작성된 자바 어플리케이션이 데이터 베이스와 통신 가능

 

구성 

자바 어플리케이션 -> JDBC API -> JDBC 드라이버 -> 데이터 베이스

 

JDBC 흐름

JDBC 드라이버 로드 -> DB 연결 -> 데이터 추가 및 수정 (SQL 문 사용) -> 결과처리 -> DB 연결 종료

 

JDBC 소스 예제 (간단한 SELECT문 사용 예제)

=> MySQL DB 내 customers 테이블 데이터 조회

import java.sql.*;

public class JdbcExample {
    public static void main(String[] args) {
        // JDBC 드라이버 로드
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            System.out.println("JDBC 드라이버를 찾을 수 없습니다.");
            e.printStackTrace();
            return;
        }

        // 데이터베이스 연결 설정
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "root";
        String password = "password";
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;

        try {
            connection = DriverManager.getConnection(url, username, password);

            // SQL 문 실행
            statement = connection.createStatement();
            String sql = "SELECT * FROM customers";
            resultSet = statement.executeQuery(sql);

            // 결과 처리
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String email = resultSet.getString("email");
                System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
            }
        } catch (SQLException e) {
            System.out.println("데이터베이스 연결 오류");
            e.printStackTrace();
        } finally {
            // 연결 해제
            try {
                if (resultSet != null)
                    resultSet.close();
                if (statement != null)
                    statement.close();
                if (connection != null)
                    connection.close();
            } catch (SQLException e) {
                System.out.println("데이터베이스 연결 해제 오류");
                e.printStackTrace();
            }
        }
    }
}

 

반응형