JSP Database Integration


JSP와 데이터베이스 연동 (JSP and Database Integration)

JDBC 개요 (Overview of JDBC)

JDBC(Java Database Connectivity)는 자바 프로그램이 다양한 데이터베이스와 상호작용할 수 있도록 해주는 API입니다. JDBC를 사용하면 자바 애플리케이션에서 데이터베이스에 연결하고, SQL 쿼리를 실행하며, 결과를 처리할 수 있습니다. JDBC는 다음과 같은 주요 구성 요소를 포함합니다:

  • DriverManager: 데이터베이스 드라이버를 관리하고, 데이터베이스 연결을 설정합니다.
  • Connection: 데이터베이스와의 연결을 나타냅니다.
  • Statement: SQL 문을 실행하는 데 사용됩니다.
  • ResultSet: SQL 쿼리의 결과를 저장합니다.
  • SQLException: 데이터베이스 관련 오류를 처리합니다.

데이터베이스 연결 설정 (Setting Up Database Connection)

JSP에서 JDBC를 사용하여 데이터베이스에 연결하려면 다음 단계를 따릅니다:

  1. JDBC 드라이버를 로드합니다.
  2. 데이터베이스에 연결합니다.
  3. SQL 문을 실행합니다.
  4. 결과를 처리합니다.
  5. 연결을 닫습니다.

예제:

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

public class DatabaseConnection {
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        // 1. JDBC 드라이버를 로드합니다.
        Class.forName("com.mysql.cj.jdbc.Driver");

        // 2. 데이터베이스에 연결합니다.
        String url = "jdbc:mysql://localhost:3306/mydatabase";
        String username = "root";
        String password = "password";
        return DriverManager.getConnection(url, username, password);
    }
}

위 예제는 MySQL 데이터베이스에 연결하는 방법을 보여줍니다. JDBC 드라이버를 로드하고, 데이터베이스 URL, 사용자 이름, 비밀번호를 사용하여 연결을 설정합니다.

데이터베이스 CRUD 작업 (Database CRUD Operations)

CRUD(Create, Read, Update, Delete) 작업은 데이터베이스에서 기본적으로 수행되는 작업입니다. 다음은 JSP에서 JDBC를 사용하여 CRUD 작업을 수행하는 방법입니다:

  1. Create: 데이터를 삽입합니다.
  2. Read: 데이터를 조회합니다.
  3. Update: 데이터를 수정합니다.
  4. Delete: 데이터를 삭제합니다.

데이터베이스 테이블 생성:

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(50) NOT NULL,
    password VARCHAR(50) NOT NULL,
    email VARCHAR(100)
);

데이터 삽입 예제 (Create):

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

public class UserDAO {
    public void insertUser(String username, String password, String email) throws SQLException, ClassNotFoundException {
        Connection conn = DatabaseConnection.getConnection();
        String sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, username);
        pstmt.setString(2, password);
        pstmt.setString(3, email);
        pstmt.executeUpdate();
        pstmt.close();
        conn.close();
    }
}

데이터 조회 예제 (Read):

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

public class UserDAO {
    public void getUser(int userId) throws SQLException, ClassNotFoundException {
        Connection conn = DatabaseConnection.getConnection();
        String sql = "SELECT * FROM users WHERE id = ?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, userId);
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            System.out.println("Username: " + rs.getString("username"));
            System.out.println("Email: " + rs.getString("email"));
        }
        rs.close();
        pstmt.close();
        conn.close();
    }
}

데이터 수정 예제 (Update):

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

public class UserDAO {
    public void updateUser(int userId, String username, String email) throws SQLException, ClassNotFoundException {
        Connection conn = DatabaseConnection.getConnection();
        String sql = "UPDATE users SET username = ?, email = ? WHERE id = ?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, username);
        pstmt.setString(2, email);
        pstmt.setInt(3, userId);
        pstmt.executeUpdate();
        pstmt.close();
        conn.close();
    }
}

데이터 삭제 예제 (Delete):

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

public class UserDAO {
    public void deleteUser(int userId) throws SQLException, ClassNotFoundException {
        Connection conn = DatabaseConnection.getConnection();
        String sql = "DELETE FROM users WHERE id = ?";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setInt(1, userId);
        pstmt.executeUpdate();
        pstmt.close();
        conn.close();
    }
}

DAO 패턴과 JSP (DAO Pattern and JSP)

DAO(Data Access Object) 패턴은 데이터베이스와의 상호작용을 캡슐화하는 디자인 패턴입니다. DAO 클래스는 데이터베이스 작업(CRUD)을 수행하는 메서드를 포함하며, JSP 페이지에서는 이 메서드를 호출하여 데이터를 처리합니다.

DAO 클래스:

public class UserDAO {
    // ... CRUD 메서드들 ...
}

JSP 페이지에서 DAO 사용:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.example.UserDAO" %>
<%@ page import="java.sql.SQLException" %>
<html>
<head>
    <title>JSP와 데이터베이스 연동 예제</title>
</head>
<body>
    <h1>사용자 목록</h1>
    <%
        UserDAO userDAO = new UserDAO();
        try {
            userDAO.getUser(1); // 특정 사용자 조회
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    %>
</body>
</html>

위 예제는 JSP 페이지에서 UserDAO 클래스를 사용하여 데이터베이스와 상호작용하는 방법을 보여줍니다. DAO 패턴을 사용하면 코드의 재사용성과 유지보수성이 높아집니다.

종합 예제 (Comprehensive Example)

다음은 JSP와 데이터베이스 연동을 종합적으로 보여주는 예제입니다.

  1. DatabaseConnection.java: import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DatabaseConnection { public static Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "password"; return DriverManager.getConnection(url, username, password); } }
  2. UserDAO.java: import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class UserDAO { public void insertUser(String username, String password, String email) throws SQLException, ClassNotFoundException { Connection conn = DatabaseConnection.getConnection(); String sql = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, username); pstmt.setString(2, password); pstmt.setString(3, email); pstmt.executeUpdate(); pstmt.close(); conn.close(); }public void getUser(int userId) throws SQLException, ClassNotFoundException { Connection conn = DatabaseConnection.getConnection(); String sql = "SELECT * FROM users WHERE id = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, userId); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { System.out.println("Username: " + rs.getString("username")); System.out.println("Email: " + rs.getString("email")); } rs.close(); pstmt.close(); conn.close(); } public void updateUser(int userId, String username, String email) throws SQLException, ClassNotFoundException { Connection conn = DatabaseConnection.getConnection(); String sql = "UPDATE users SET username = ?, email = ? WHERE id = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, username); pstmt.setString(2, email); pstmt.setInt(3, userId); pstmt.executeUpdate(); pstmt.close(); conn.close(); } public void deleteUser(int userId) throws SQLException, ClassNotFoundException { Connection conn = DatabaseConnection.getConnection(); String sql = "DELETE FROM users WHERE id = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, userId); pstmt.executeUpdate(); pstmt.close(); conn.close(); }}
  3. index.jsp:
    “`jsp
    <%@ page contentType=”text/html;charset=UTF-8

” language=”java” %>
<%@ page import=”com.example.UserDAO” %>
<%@ page import=”java.sql.SQLException” %>

JSP와 데이터베이스 연동 예제

사용자 관리

<%
UserDAO userDAO = new UserDAO();
try {
// 사용자 추가
userDAO.insertUser(“john_doe”, “password123”, “john@example.com”);

            // 사용자 조회
            out.println("<h2>사용자 정보</h2>");
            userDAO.getUser(1);

            // 사용자 수정
            userDAO.updateUser(1, "john_doe_updated", "john_updated@example.com");

            // 사용자 삭제
            userDAO.deleteUser(1);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    %>
</body>
</html>
```

이 종합 예제는 JSP와 JDBC를 사용하여 데이터베이스에 연결하고, CRUD 작업을 수행하며, DAO 패턴을 통해 코드의 구조화와 재사용성을 높이는 방법을 보여줍니다. 이를 통해 JSP와 데이터베이스 연동의 전체 과정을 이해할 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *