> 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-preparedstatement.md).

# Creando a capa de DAO con PreparedStatement

Un dos problemas que ten traballar con Statement é que é vulnerable a un SQL Injection.

{% hint style="warning" %}
**SQL Injection:** <https://es.stackoverflow.com/questions/10518/qu%C3%A9-es-la-inyecci%C3%B3n-sql-y-c%C3%B3mo-puedo-evitarla>
{% endhint %}

Para evitar este tipo de problemas, recomendase traballar con PreparedStatement dentro da capa de acceso a datos. A migración da nosa clase alumno a utilización de esta sentenza quedaria da seguinte forma:

```java
package DAO;

import Modelo.Alumno;
import Util.Lector;

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

public class AlumnoDAOPrepStat {
    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());
             PreparedStatement ps = con.prepareStatement(sql);){
            ResultSet rs = ps.executeQuery();
            while (rs.next()){
                /*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 = ?";
        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()){
                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 (?,?,?)";
        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, a.getNombre());
            ps.setString(2, a.getApellido());
            ps.setObject(3, a.getFechaNac());

            int filasAfectadas = ps.executeUpdate();

            if (filasAfectadas > 0) {
                ResultSet rs = ps.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 = ?, apellido = ?, fechaNac = ? WHERE id = ?";
        try (Connection con = DriverManager.getConnection(Lector.getInstancia().getServidor(), Lector.getInstancia().getUsuario(), Lector.getInstancia().getContraseña());
             PreparedStatement ps = con.prepareStatement(sql)) {
            System.out.println("Alumno actualizar: " + a);
            ps.setString(1, a.getNombre());
            ps.setString(2, a.getApellido());
            ps.setObject(3, a.getFechaNac());
            ps.setInt(4, a.getId());

            int filasAfectadas = ps.executeUpdate();
            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 = ?";
        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/ud8-persistencia-en-bases-de-datos/escenario-de-traballo/creando-a-capa-de-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.
