Sobes.tech
Middle

What would a JDBC solution look like for retrieving all people from the persons table born after a certain date?

sobes.tech AI

Answer from AI

To retrieve all people from the persons table born after a certain date, you can use the following JDBC code example:

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class PersonDAO {
    private Connection connection;

    public PersonDAO(Connection connection) {
        this.connection = connection;
    }

    public List<Person> getPersonsBornAfter(Date date) throws SQLException {
        String sql = "SELECT id, name, birth_date FROM persons WHERE birth_date > ?";
        List<Person> persons = new ArrayList<>();

        try (PreparedStatement stmt = connection.prepareStatement(sql)) {
            stmt.setDate(1, date);
            try (ResultSet rs = stmt.executeQuery()) {
                while (rs.next()) {
                    Person p = new Person();
                    p.setId(rs.getInt("id"));
                    p.setName(rs.getString("name"));
                    p.setBirthDate(rs.getDate("birth_date"));
                    persons.add(p);
                }
            }
        }
        return persons;
    }
}

// Person class for example
class Person {
    private int id;
    private String name;
    private Date birthDate;

    // getters and setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public Date getBirthDate() { return birthDate; }
    public void setBirthDate(Date birthDate) { this.birthDate = birthDate; }
}

This example uses PreparedStatement for safe parameter substitution, preventing SQL injection. The method returns a list of Person objects born after the specified date.