package CHAPTER15;

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

public class C15_05_InsertQuery {
	private static final String URL = "jdbc:mysql://localhost:3306/course";
	private static final String USER = "root";
	private static final String PASSWORD = "123456789";

	// 회원 데이터를 삽입하는 메서드
	public static void insertMember(String username, String password, String email, String phone, String birthdate, Connection conn) throws SQLException{
		String query = "INSERT INTO members (username, password, email, phone, birthdate) VALUES (?, ?, ?, ?, ?)";

		PreparedStatement preparedStatement = conn.prepareStatement(query);

		// 파라미터 설정
		preparedStatement.setString(1, username);
		preparedStatement.setString(2, password);
		preparedStatement.setString(3, email);
		preparedStatement.setString(4, phone);
		preparedStatement.setString(5, birthdate);

		// 쿼리 실행
		int rowsAffected = preparedStatement.executeUpdate();
		System.out.println(rowsAffected + " member(s) inserted successfully.");
	}

	// 모든 회원 데이터를 조회하는 메서드
	public static void getAllMembers(Connection conn) throws SQLException {
		String query = "SELECT * FROM members";

		PreparedStatement preparedStatement = conn.prepareStatement(query);
		ResultSet resultSet = preparedStatement.executeQuery();

		System.out.println("\nAll Members:");
		while (resultSet.next()) {
			System.out.println("ID: " + resultSet.getInt("member_id") 
					+ ", Username: " + resultSet.getString("username")
					+ ", Email: " + resultSet.getString("email") 
					+ ", Phone: " + resultSet.getString("phone")
					+ ", Birthdate: " + resultSet.getDate("birthdate"));
		}
	}

	public static void main(String[] args) {
		try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {

			// 회원 데이터 삽입 (예제 데이터)
			insertMember("Moon_doe", "securepass123", "john.doe@example.com", "010-1234-5678", "1990-05-15", conn);

			// 모든 회원 정보 조회
			getAllMembers(conn);
			
		} catch (SQLException e) {
			System.err.println("Database connection failed: " + e.getMessage());
			e.printStackTrace();
		}
	}
}
