> 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/ud8-persistencia-en-bases-de-datos/escenario-de-traballo/creando-a-capa-de-dao-con-statement.md).

# Creando a capa de DAO con Statement

A capa DAO ten a responsabilidade de realizar o acceso a datos da aplicación, mapeando o contido da base de datos a súa clase correspondente da capa Modelo ou Entity.

Cando empregamos o **patrón DAO, é habitual que para cada clase do modelo, exista a súa clase de acceso a datos.** A continuación mostrase un exemplo de operacións CRUD para Alumno:&#x20;

```java
package DAO;

import Util.Lector;
import Modelo.Alumno;

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

public class AlumnoDAOImpl {

    public List<Alumno> findAll() {
        List<Alumno> lista = new ArrayList<>();
        String sql = "SELECT * FROM alumnos";
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
                Statement s = con.createStatement()){
            ResultSet rs = s.executeQuery(sql);
            while (rs.next()){
            //Es posible hacer el get por el valor del campo y por el valor del id
                /*Alumno alumno = new Alumno(
                        rs.getInt("id"),
                        rs.getString("nombre"),
                        rs.getString("apellido"),
                        rs.getDate("fechaNac").toLocalDate()
                );*/
                Alumno alumno = new Alumno(
                        rs.getInt(1),
                        rs.getString(2),
                        rs.getString(3),
                        rs.getDate(4).toLocalDate()
                );
                lista.add(alumno);
            }

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


    public Optional<Alumno> findById(int id) {
        Optional<Alumno> res;
        String sql = "SELECT * FROM alumnos WHERE id = " + id;
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
        Statement s = con.createStatement()){
            ResultSet rs = s.executeQuery(sql);

            if (rs.next()){
                Alumno alumno = new Alumno(
                        rs.getInt("id"),
                        rs.getString("nombre"),
                        rs.getString("apellido"),
                        rs.getDate("fechaNac").toLocalDate()
                );
                res = Optional.of(alumno);
                return res;
            }

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

    public int insert(Alumno a) {
        String sql = "INSERT INTO alumnos (nombre, apellido, fechaNac) VALUES (" +
                "'" + a.getNombre() + "', " +
                "'" + a.getApellido() + "', " +
                "'" + a.getFechaNac().toString() + "')";
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             Statement s = con.createStatement()) {

            int filasAfectadas = s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);

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

    public Optional<Alumno> update(Alumno a) {
        String sql = "UPDATE alumnos SET " +
                "nombre = '" + a.getNombre() + "', " +
                "apellido = '" + a.getApellido() + "', " +
                "fechaNac = '" + a.getFechaNac().toString() + "' " +
                "WHERE id = " + a.getId();
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             Statement s = con.createStatement()) {

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

    public boolean remove(int id) {
        String sql = "DELETE FROM alumnos WHERE id = " + id;
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             Statement s = con.createStatement()) {
            int filasAfectadas = s.executeUpdate(sql);
            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/ud8-persistencia-en-bases-de-datos/escenario-de-traballo/creando-a-capa-de-dao-con-statement.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.
