> For the complete documentation index, see [llms.txt](https://educacion.gitbook.io/programacion/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://educacion.gitbook.io/programacion/exercicios-java/ud8-solucions/dao-con-preparedstatement.md).

# DAO con PreparedStatement

```java
package DAO;

import Util.Lector;
import Modelo.Profesor;

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

public class ProfesorDAOPrepStat {

    public List<Profesor> findAll() {
        List<Profesor> lista = new ArrayList<>();
        String sql = "SELECT * FROM profesores";
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             PreparedStatement ps = con.prepareStatement(sql)) {

            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                Profesor profesor = new Profesor(
                        rs.getInt(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getDate(4).toLocalDate(),
                        rs.getInt(5)
                );
                lista.add(profesor);
            }

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return lista;
    }

    public Optional<Profesor> findById(int id) {
        String sql = "SELECT * FROM profesores WHERE id = ?";
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             PreparedStatement ps = con.prepareStatement(sql)) {

            ps.setInt(1, id);
            ResultSet rs = ps.executeQuery();

            if (rs.next()) {
                Profesor profesor = new Profesor(
                        rs.getInt("id"),
                        rs.getString("nombre"),
                        rs.getString("email"),
                        rs.getDate("fecha_contrato").toLocalDate(),
                        rs.getInt("id_departamento")
                );
                return Optional.of(profesor);
            }

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return Optional.empty();
    }

    public int insert(Profesor p) {
        String sql = "INSERT INTO profesores (nombre, email, fecha_contrato, id_departamento) VALUES (?, ?, ?, ?)";
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             PreparedStatement ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            ps.setString(1, p.getNombre());
            ps.setString(2, p.getEmail());
            ps.setObject(3, p.getFechaContrato()); // Uso de setObject para LocalDate
            ps.setInt(4, p.getIdDepartamento());

            int filasAfectadas = ps.executeUpdate();

            if (filasAfectadas > 0) {
                ResultSet rs = ps.getGeneratedKeys();
                if (rs.next()) {
                    int id = rs.getInt(1);
                    p.setId(id);
                    return id;
                }
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return -1;
    }

    public Optional<Profesor> update(Profesor p) {
        String sql = "UPDATE profesores SET nombre = ?, email = ?, fecha_contrato = ?, id_departamento = ? WHERE id = ?";
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             PreparedStatement ps = con.prepareStatement(sql)) {

            ps.setString(1, p.getNombre());
            ps.setString(2, p.getEmail());
            ps.setObject(3, p.getFechaContrato());
            ps.setInt(4, p.getIdDepartamento());
            ps.setInt(5, p.getId());

            int filasAfectadas = ps.executeUpdate();
            if (filasAfectadas > 0) {
                return Optional.of(p);
            }
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return Optional.empty();
    }

    public boolean remove(int id) {
        String sql = "DELETE FROM profesores WHERE id = ?";
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             PreparedStatement ps = con.prepareStatement(sql)) {

            ps.setInt(1, id);
            int filasAfectadas = ps.executeUpdate();
            return filasAfectadas > 0;

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
        return false;
    }
}

```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://educacion.gitbook.io/programacion/exercicios-java/ud8-solucions/dao-con-preparedstatement.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
