콩딱일상

테이블 모듈 매턴 본문

테이블 모듈 매턴

콩이캠퍼 2024. 10. 3. 13:07

Table Module은 DB의 테이블 단위로 비즈니스 로직을 처리하는 클래스로 분리를 합니다.

전체 비즈니스의 흐름은 DB 테이블 단위의 클래스를 이용하여 처리 합니다.

JDBC(Java Database Connectivity)가 제공하는 ResultSet이나, RecordSet, DataSet을 선언하고 기능을 추가해서도 사용합니다.

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

// User 테이블을 관리하는 테이블 모듈
public class UserTable {

    private Connection connection;

    // 생성자를 통해 데이터베이스 연결을 받습니다.
    public UserTable(Connection connection) {
        this.connection = connection;
    }

    // User 클래스는 테이블의 각 레코드를 나타냅니다.
    public static class User {
        public int id;
        public String name;
        public String email;

        public User(int id, String name, String email) {
            this.id = id;
            this.name = name;
            this.email = email;
        }

        @Override
        public String toString() {
            return "User{id=" + id + ", name='" + name + "', email='" + email + "'}";
        }
    }

    // ID로 사용자를 가져오는 메서드
    public User getUserById(int id) throws SQLException {
        String query = "SELECT id, name, email FROM users WHERE id = ?";
        try (PreparedStatement stmt = connection.prepareStatement(query)) {
            stmt.setInt(1, id);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return new User(rs.getInt("id"), rs.getString("name"), rs.getString("email"));
                }
            }
        }
        return null;
    }

    // 새로운 사용자를 추가하는 메서드
    public void createUser(String name, String email) throws SQLException {
        String query = "INSERT INTO users (name, email) VALUES (?, ?)";
        try (PreparedStatement stmt = connection.prepareStatement(query)) {
            stmt.setString(1, name);
            stmt.setString(2, email);
            stmt.executeUpdate();
        }
    }

    // 사용자의 이메일을 업데이트하는 메서드
    public void updateUserEmail(int id, String email) throws SQLException {
        String query = "UPDATE users SET email = ? WHERE id = ?";
        try (PreparedStatement stmt = connection.prepareStatement(query)) {
            stmt.setString(1, email);
            stmt.setInt(2, id);
            stmt.executeUpdate();
        }
    }

    // 사용자를 삭제하는 메서드
    public void deleteUser(int id) throws SQLException {
        String query = "DELETE FROM users WHERE id = ?";
        try (PreparedStatement stmt = connection.prepareStatement(query)) {
            stmt.setInt(1, id);
            stmt.executeUpdate();
        }
    }
}

'' 카테고리의 다른 글

독서가 종이에서 e-book으로 (feat 밀리의 서재?)  (0) 2021.10.08