package CHAPTER15;

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

public class C15_04_SelectSortlimitQuery {
	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 getRecentMembersByEmail(Connection connection) throws SQLException {
		String query = "SELECT * FROM members ORDER BY username DESC LIMIT 5";

		PreparedStatement preparedStatement = connection.prepareStatement(query);

		ResultSet resultSet = preparedStatement.executeQuery();

		System.out.println("\nRecent Members Details:");
		boolean hasResults = false;
		while (resultSet.next()) {
			hasResults = true;
			System.out.println("ID: " + resultSet.getInt("member_id") 
					+ ", Username: " + resultSet.getString("username")
					+ ", Email: " + resultSet.getString("email") 
					+ ", Phone: " + resultSet.getString("phone")
					+ ", Birthdate: " + resultSet.getDate("birthdate"));
		}

		if (!hasResults) {
			System.out.println("No recent members found.");
		}
	}

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

		} catch (SQLException e) {
			System.err.println("Database connection failed: " + e.getMessage());
			e.printStackTrace();
		}
	}
}
