No tienes acceso a esta clase

¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera

Curso de Java SE: SQL y Bases de Datos

Curso de Java SE: SQL y Bases de Datos

Ana Fernanda Gutierrez Villanueva

Ana Fernanda Gutierrez Villanueva

Insertar Datos en Java

12/22
Recursos

En el método save(Employee employee) implementamos la funcionalidad para insertar un nuevo registro de empleado en la base de datos.

Dentro del método, definimos una consulta SQL de inserción y la almacenamos en una variable de tipo String. Luego, utilizamos un objeto PreparedStatement para preparar la consulta y asignar los valores de los parámetros.

Una vez que todos los valores se han asignado, ejecutamos el método executeUpdate() del PreparedStatement para ejecutar la consulta y realizar la inserción en la base de datos.

Aportes 18

Preguntas 1

Ordenar por:

¿Quieres ver más aportes, preguntas y respuestas de la comunidad?

En el método save(Employee employee) implementamos la funcionalidad para insertar un nuevo registro de empleado en la base de datos.

Dentro del método, definimos una consulta SQL de inserción y la almacenamos en una variable de tipo String. Luego, utilizamos un objeto PreparedStatement para preparar la consulta y asignar los valores de los parámetros.

Una vez que todos los valores se han asignado, ejecutamos el método executeUpdate() del PreparedStatement para ejecutar la consulta y realizar la inserción en la base de datos.

Esta fue la forma que encontré de acuerdo a la clase

    @Override
    public void save(Employee employee) throws SQLException {
        String sql;

        if (employee.getId() < 1) {
            sql = "INSERT INTO employees(first_name, pa_surname, ma_surname, email, salary) VALUES(?, ?, ?, ?, ?)";
        } else {
            sql = "UPDATE employees set first_name = ?, pa_surname = ?, ma_surname = ?, email = ?, salary = ? WHERE id = ?";
        }

        try(PreparedStatement myStmt = getConnection().prepareStatement(sql)){

            myStmt.setString(1, employee.getFirst_name());
            myStmt.setString(2, employee.getPa_surname());
            myStmt.setString(3, employee.getMa_surname());
            myStmt.setString(4, employee.getEmail());
            myStmt.setFloat(5, employee.getSalary());

            if (employee.getId() != 0){
                myStmt.setInt(6, employee.getId());
            }

            int rows = myStmt.executeUpdate();

            if (rows > 0) {
                System.out.println("All that's good");
            } else {
                System.out.println("Something is going wrong");
            }
        }
    }```
Buen día, Esta es mi solución al reto (Actualización): Código interface Repository: ![](https://static.platzi.com/media/user_upload/image-3d75f6a0-5dda-4f77-a6be-c82694e86262.jpg) Código en class EmployeeRepository: Se realiza validación si existe el empleado por id, como se indica en el reto, si existe se actualiza, si no existe se crea el usuario. En el punto, pensaría que, si no existe el empleado se puede indicar con un mensaje que no existe y tiene la opción de crearlo o en su defecto seguir intentando colocar el id correcto. ![](https://static.platzi.com/media/user_upload/image-c383916c-7fa7-4247-bc2a-13849d297931.jpg) main.java ![](https://static.platzi.com/media/user_upload/image-5729ccce-9e33-467e-ac58-c51684b7bfe1.jpg) Resultado si existe: ![](https://static.platzi.com/media/user_upload/image-b5cc34d9-51c9-4c14-826c-6fb48dfd873f.jpg) BD antes de modificación: ![](https://static.platzi.com/media/user_upload/image-99e16a71-6d11-4f90-8c91-6f4e08f09b3d.jpg) BD después de modificación: ![](https://static.platzi.com/media/user_upload/image-b48c6591-6d82-47e4-9605-636226504f93.jpg) Resultado si no existe: ![](https://static.platzi.com/media/user_upload/image-7ef5ecf8-ca4a-4155-b091-31ee8ffb068e.jpg) ![](https://static.platzi.com/media/user_upload/image-a8681c44-0d8a-418b-9f40-40b7427f2d00.jpg) BD: ![](https://static.platzi.com/media/user_upload/image-a767c185-136c-4257-93b6-b514d1ffbd9c.jpg) Espero sea de ayuda para ustedes. Saludos y éxitos.
Esta es la solución a lo requerido(Si nos dan un id mayor a cero se realiza la actualización de lo contrario una inserción) hardcodeado los valores (No es una buena practica) pero es mas claro la implementación (Main) base de datos Oracle y campos diferentes a los planteados. ```js package org.example.empresa.main; import org.example.empresa.model.Employee; import org.example.empresa.repository.EmployeeRepository; import org.example.empresa.repository.IRepository; import org.example.empresa.util.DatabaseConnection; import java.sql.*; import java.util.Scanner; public class Main { public static void main(String[] args) { try (Connection myConn = DatabaseConnection.getInstance()) { System.out.println("--Bienvenido a ingreso de usuarios:--"); Scanner scanner = new Scanner(System.in); System.out.println("Si deseas actualizar ingresa un ID a actualizar"); int option = scanner.nextInt(); if (option > 0) { IRepository<Employee> repository = new EmployeeRepository(); Employee employee = new Employee(); employee.setSalary(2500); employee.setId(23); repository.update(employee); System.out.println("Cliente actualizado"); } else { System.out.println("-----Insertando un cliente------"); IRepository<Employee> repository = new EmployeeRepository(); Employee employee = new Employee(); employee.setNombre("Restrepo"); employee.setApellido("Segura"); employee.setSalary(1000); repository.save(employee); } } catch (SQLException e) { throw new RuntimeException(e); } } } ```

Propuesta solución a reto

public void save(Landscapes landscape, Integer id) throws SQLException {
        String sql = null;
        String sqlins = "INSERT INTO landscapes (NameLands,Continent) VALUES (?,?)";
        String sqlupd = "UPDATE landscapes SET NameLands = ?, Continent = ? WHERE IDLands = "+id;
        if(id == 0)
            sql = sqlins;
        else
            sql = sqlupd;
        try (PreparedStatement myStamt = getConnection().prepareStatement(sql)) {
                myStamt.setString(1, landscape.getNameLands());
                myStamt.setString(2, landscape.getContinent());
                myStamt.executeUpdate();
            }
    }
Dado que el id en la clase Employee es de tipo Integer y no int, puede ser null, por lo tanto en vez de preguntar si el id es mayor a 0 simplemente pregunto si es igual o no a null:public void save(Employee employee) throws SQLException { String sql; if (employee.getId() == null) { sql = "INSERT INTO employees (first\_name, pa\_surname, ma\_surname, email, salary) VALUES (?, ?, ?, ?, ?)"; } else { sql = "UPDATE employees SET first\_name = ?, pa\_surname = ?, ma\_surname = ?, email = ?, salary = ? WHERE id = " + employee.getId(); } try ( PreparedStatement stmt = getConnection().prepareStatement(sql); ) { stmt.setString(1, employee.getFirst\_name()); stmt.setString(2, employee.getPa\_surname()); stmt.setString(3, employee.getMa\_surname()); stmt.setString(4, employee.getEmail()); stmt.setFloat(5, employee.getSalary()); stmt.executeUpdate(); } } ```js public void save(Employee employee) throws SQLException { String sql; if (employee.getId() == null) { sql = "INSERT INTO employees (first_name, pa_surname, ma_surname, email, salary) VALUES (?, ?, ?, ?, ?)"; } else { sql = "UPDATE employees SET first_name = ?, pa_surname = ?, ma_surname = ?, email = ?, salary = ? WHERE id = " + employee.getId(); } try ( PreparedStatement stmt = getConnection().prepareStatement(sql); ) { stmt.setString(1, employee.getFirst_name()); stmt.setString(2, employee.getPa_surname()); stmt.setString(3, employee.getMa_surname()); stmt.setString(4, employee.getEmail()); stmt.setFloat(5, employee.getSalary()); stmt.executeUpdate(); } } ```
```js // IRepository.java public interface IRepository <T> { List<T> findAll() throws SQLException; T getById(Integer id) throws SQLException; boolean save(T record) throws SQLException; boolean update(int id, T record) throws SQLException; Integer delete(Integer id) throws SQLException; } // EmployeeRepository.java @Override public boolean update(int id, Employee record) throws SQLException { String sentence = "UPDATE employees SET first_name=?, last_name=? WHERE id=?"; try(PreparedStatement statement = getConnection().prepareStatement(sentence)) { statement.setString(1, record.getFirst_name()); statement.setString(2, record.getLast_name()); statement.setInt(3, id); int rows = statement.executeUpdate(); return rows == 1; } } // Main.java public static void main(String[] args) throws SQLException { try { IRepository<Employee> repository = new EmployeeRepository(); int idToUpdate = 30; Employee employee = repository.getById(idToUpdate); if (employee == null) { System.out.println("Employee not found"); return; } employee.setFirst_name("Troncha"); employee.setLast_name("Toro"); boolean done = repository.update(idToUpdate, employee); String msg = done ? "An employee has been updated" : "Employee could not be updated"; System.out.println(msg); } catch (SQLException e) { System.out.println("Something went wrong"); e.printStackTrace(); } } ```// IRepository.java public interface IRepository \<T> { List\<T> findAll() throws SQLException; T getById(Integer id) throws SQLException; boolean save(T record) throws SQLException; boolean update(int id, T record) throws SQLException; Integer delete(Integer id) throws SQLException; } // EmployeeRepository.java @Override public boolean update(int id, Employee record) throws SQLException { String sentence = "UPDATE employees SET first\_name=?, last\_name=? WHERE id=?"; try(PreparedStatement statement = getConnection().prepareStatement(sentence)) { statement.setString(1, record.getFirst\_name()); statement.setString(2, record.getLast\_name()); statement.setInt(3, id); int rows = statement.executeUpdate(); return rows == 1; } } // Main.java public static void main(String\[] args) throws SQLException { try { IRepository\<Employee> repository = new EmployeeRepository(); int idToUpdate = 30; Employee employee = repository.getById(idToUpdate); if (employee == null) { System.out.println("Employee not found"); return; } employee.setFirst\_name("Troncha"); employee.setLast\_name("Toro"); boolean done = repository.update(idToUpdate, employee); String msg = done ? "An employee has been updated" : "Employee could not be updated"; System.out.println(msg); } catch (SQLException e) { System.out.println("Something went wrong"); e.printStackTrace(); } }
Aquí con un boolean: `public void save(Employee employee) throws SQLException {` ` String sql;` ` Boolean actualiza = employee.getId() != null && employee.getId() > 0;` ` if (actualiza) {` ` sql = "UPDATE employees SET first_name = ?,pa_surname=?,ma_surname=?,email=?,salary=? WHERE id = ?";` ` }else {` ` sql = "INSERT INTO employees(first_name,pa_surname,ma_surname,email,salary) VALUES (?, ?, ?,?,?)";` ` }` ` try(PreparedStatement stm = getConnection().prepareStatement(sql)){` ` if (actualiza) {stm.setInt(6,employee.getId());}` ` stm.setString(1,employee.getFirst_name());` ` stm.setString(2,employee.getPa_surname());` ` stm.setString(3,employee.getMa_surname());` ` stm.setString(4,employee.getEmail());` ` stm.setFloat(5,employee.getSalary());` ` stm.executeUpdate();` ` } ` `}`
`@Override` `public void save(Employee employee) throws SQLException {` ` String query = "";` ` if (employee.getId() != null) {` ` query = "UPDATE employees SET first_name = ?, pa_surname = ?, ma_surname = ?, email = ?, salary = ? WHERE id = ?";` ` } else {` ` query = "INSERT INTO employees (first_name,pa_surname,ma_surname,email,salary) VALUES (?,?,?,?,?)";` ` }` ` try (PreparedStatement statement = getConnection().prepareStatement(query)) {` ` statement.setString(1, employee.getFirstName());` ` statement.setString(2, employee.getPaSurname());` ` statement.setString(3, employee.getMaSurname());` ` statement.setString(4, employee.getEmail());` ` statement.setFloat(5, employee.getSalary());` ` if (employee.getId() != null) {` ` statement.setInt(6, employee.getId());` ` }` ` statement.executeUpdate();` ` }` `}`
@Override public void save(Employee employee) throws SQLException { String query = ""; if (employee.getId() != null) { query = "UPDATE employees SET first\_name = ?, pa\_surname = ?, ma\_surname = ?, email = ?, salary = ? WHERE id = ?"; } else { query = "INSERT INTO employees (first\_name,pa\_surname,ma\_surname,email,salary) VALUES (?,?,?,?,?)"; } try (PreparedStatement statement = getConnection().prepareStatement(query)) { statement.setString(1, employee.getFirstName()); statement.setString(2, employee.getPaSurname()); statement.setString(3, employee.getMaSurname()); statement.setString(4, employee.getEmail()); statement.setFloat(5, employee.getSalary()); if (employee.getId() != null) { statement.setInt(6, employee.getId()); } statement.executeUpdate(); } }
![]()![](https://static.platzi.com/media/user_upload/image-66651d24-1887-4b43-801b-e3251fc654d5.jpg) ```java ejecuté este metodo y me dice que tengo un error en la sintaxis de l sql ¿alguien que me pueda indicar el error? ```
private Connection getConnection() throws SQLException { return CONECTARBD.getInstance(); } @Override public List\<PERSONA> LeerTodos() throws SQLException { List\<PERSONA> personas =new ArrayList<>(); try(Statement myStat =getConnection().createStatement(); ResultSet myRes=myStat.executeQuery("Select \* from Persona")){ while(myRes.next()){ PERSONA e=CrearPersona(myRes); personas.add(e); } } return personas; } @Override public PERSONA LeerporId(Integer Id) throws SQLException { PERSONA persona =null; try(PreparedStatement mystat= getConnection().prepareStatement("Select \* from persona where IdPersona=?")){ mystat.setInt(1,Id); try(ResultSet myRes= mystat.executeQuery()){ if(myRes.next()){ persona=CrearPersona(myRes); } } } return persona; } @Override public void Almacenar(PERSONA persona) throws SQLException { String sql="Insert into persona (IdPersona,NombrePersona) values(?,?)"; try(PreparedStatement mystat=getConnection().prepareStatement(sql)){ mystat.setInt(1,persona.getIdPersona()); mystat.setString(2,persona.getNombrePersona()); mystat.executeUpdate(); } }

Yo lo solucione de esta forma me gustaria me dieran retroalimentacion por favor:

@Override
    public void save(Employee employee) throws SQLException {


        if(employee.getId() != null && employee.getId() > 0){
           String sqlUpdate = "UPDATE " +
                    "employees SET first_name = ?, pa_surname= ?, ma_surname = ?, email = ?, salary= ?" +
                    "WHERE ID = ?";

            try(PreparedStatement myStamp = getConection().prepareStatement(sqlUpdate)){
                myStamp.setString(1, employee.getFirst_name());
                myStamp.setString(2, employee.getPa_surname());
                myStamp.setString(3, employee.getMa_surname());
                myStamp.setString(4, employee.getEmail());
                myStamp.setDouble(5, employee.getSalary());
                myStamp.setInt(6, employee.getId());

                myStamp.executeUpdate();
            }



        }else{
            String sql = "INSERT INTO employees(first_name, pa_surname, ma_surname, email, salary)" +
                    "VALUES(?, ?, ?, ?, ?)";

            try(PreparedStatement myStamp = getConection().prepareStatement(sql)){
                myStamp.setString(1, employee.getFirst_name());
                myStamp.setString(2, employee.getPa_surname());
                myStamp.setString(3, employee.getMa_surname());
                myStamp.setString(4, employee.getEmail());
                myStamp.setDouble(5, employee.getSalary());

                myStamp.executeUpdate();
            }
        }



    }
```java @Override public void save(Employee employee) throws SQLException { String sql = "INSERT INTO employees (first_name, pa_surname, ma_surname, email, salary) VALUES (?, ?, ?, ?, ?)"; if(employee.getId() != null){ sql = "UPDATE employees SET first_name=?, pa_surname=?, ma_surname=?, email=?, salary=? WHERE id=?"; } try(PreparedStatement preparedStatement = getConnection().prepareStatement(sql)){ preparedStatement.setString(1, employee.getFirstName()); preparedStatement.setString(2, employee.getPaSurname()); preparedStatement.setString(3, employee.getMaSurname()); preparedStatement.setString(4, employee.getEmail()); preparedStatement.setDouble(5, employee.getSalary()); if(employee.getId() != null){ preparedStatement.setInt(6, employee.getId()); } preparedStatement.executeUpdate(); } } ```@Override public void save(Employee employee) throws SQLException { String sql = "INSERT INTO employees (first\_name, pa\_surname, ma\_surname, email, salary) VALUES (?, ?, ?, ?, ?)"; if(employee.getId() != null){ sql = "UPDATE employees SET first\_name=?, pa\_surname=?, ma\_surname=?, email=?, salary=? WHERE id=?"; } try(PreparedStatement preparedStatement = getConnection().prepareStatement(sql)){ preparedStatement.setString(1, employee.getFirstName()); preparedStatement.setString(2, employee.getPaSurname()); preparedStatement.setString(3, employee.getMaSurname()); preparedStatement.setString(4, employee.getEmail()); preparedStatement.setDouble(5, employee.getSalary()); if(employee.getId() != null){ preparedStatement.setInt(6, employee.getId()); } preparedStatement.executeUpdate(); } }

Se me hace muy extraño que el index que toman las funciones set del statement empiecen por 1 y no por 0 😆

Aquí les dejo mi aporte para la solución de la propuesta de la profe. Usé el operador ternario. Para los que no son familiares con este tiene esta estructura: *condición* **?** *acción si se cumple la condición* **:** *acción si no se cumple.* Es una manera muy simple de resumir if's para decisiones pequeñas. `public void save(Usuario usuario) throws SQLException {` ` Boolean isUpdatable = usuario.getId() != 0; //al ser distinto de 0 significa que ya está en la DB` ` String updateSql = "UPDATE usuarios SET login = ?, password = ?, nickname = ?, email = ? WHERE id = ?";` ` String createSql = "INSERT INTO usuarios (login, password, nickname, email) VALUES (?, ?, ?, ?)";` ` try(PreparedStatement statement = getConnection().prepareStatement(isUpdatable ? updateSql : createSql)) {` ` statement.setString(1, usuario.getLogin());` ` statement.setString(2, usuario.getPassword());` ` statement.setString(3, usuario.getNickname());` ` statement.setString(4, usuario.getEmail());` ` if (isUpdatable)` ` statement.setInt(5, usuario.getId());` ` statement.executeUpdate();` ` }` `}` Espero les sea de ayuda!

Yo solamente agregue un pequeño if, aquí mi aporte:

public void save(Employee employee) throws SQLException {
        if (employee.getId() == null) {
            String sql = "INSERT INTO employees (first_name, pa_surname, ma_surname, email, salary) VALUES (?,?,?,?,?)";
            try(PreparedStatement myStamt = getConnection().prepareStatement(sql);) {
                myStamt.setString(1, employee.getFirst_name());
                myStamt.setString(2, employee.getPa_surname());
                myStamt.setString(3, employee.getMa_surname());
                myStamt.setString(4, employee.getEmail());
                myStamt.setFloat(5, employee.getSalary());
                myStamt.executeUpdate();
            }
        } else {
            String sql = "UPDATE employees SET first_name = ?, pa_surname = ?, ma_surname = ?, email = ?, salary = ? WHERE id = ?";
            try(PreparedStatement myStamt = getConnection().prepareStatement(sql);) {
                myStamt.setString(1, employee.getFirst_name());
                myStamt.setString(2, employee.getPa_surname());
                myStamt.setString(3, employee.getMa_surname());
                myStamt.setString(4, employee.getEmail());
                myStamt.setFloat(5, employee.getSalary());
                myStamt.setInt(6, employee.getId());
                myStamt.executeUpdate();
            }
        }

    }
Mi propuesta para hacer update. Primero se valida si mandaron el id y creamos un booleano en caso de que sea update. *public void* save(Employee employee) *throws* SQLException { System.out.println("El id del empleado es: "+employee.getId()); String sql; *boolean* update= *false*; *if*(employee.getId() > 0) { sql = "UPDATE employees SET first\_name = ?, pa\_surname = ?, ma\_surname = ?, email = ?, salary = ? WHERE id = ?"; update= *true*; }*else*{ sql ="INSERT INTO employees (first\_name, pa\_surname, ma\_surname, email, salary) VALUES( ?,?,?,?,?)"; } *try*( PreparedStatement myStamt = getConnection().prepareStatement(sql)){ *if*(update){ myStamt.setString(1, employee.getFirst\_name()); myStamt.setString(2, employee.getPa\_surname()); myStamt.setString(3, employee.getMa\_surname()); myStamt.setString(4, employee.getEmail()); myStamt.setFloat(5, employee.getSalary()); myStamt.setInt(6, employee.getId()); *int* rowsUpdated = myStamt.executeUpdate(); *if*(rowsUpdated>0){ System.out.println("La cantidad de filas actualizadas fueron: "+rowsUpdated); } }*else*{ myStamt.setString(1, employee.getFirst\_name()); myStamt.setString(2, employee.getPa\_surname()); myStamt.setString(3, employee.getMa\_surname()); myStamt.setString(4, employee.getEmail()); myStamt.setFloat(5, employee.getSalary()); myStamt.executeUpdate(); } } }```java public void save(Employee employee) throws SQLException { System.out.println("El id del empleado es: "+employee.getId()); String sql; boolean update= false; if(employee.getId() > 0) { sql = "UPDATE employees SET first_name = ?, pa_surname = ?, ma_surname = ?, email = ?, salary = ? WHERE id = ?"; update= true; }else{ sql ="INSERT INTO employees (first_name, pa_surname, ma_surname, email, salary) VALUES( ?,?,?,?,?)"; } try( PreparedStatement myStamt = getConnection().prepareStatement(sql)){ if(update){ myStamt.setString(1, employee.getFirst_name()); myStamt.setString(2, employee.getPa_surname()); myStamt.setString(3, employee.getMa_surname()); myStamt.setString(4, employee.getEmail()); myStamt.setFloat(5, employee.getSalary()); myStamt.setInt(6, employee.getId()); int rowsUpdated = myStamt.executeUpdate(); if(rowsUpdated>0){ System.out.println("La cantidad de filas actualizadas fueron: "+rowsUpdated); } }else{ myStamt.setString(1, employee.getFirst_name()); myStamt.setString(2, employee.getPa_surname()); myStamt.setString(3, employee.getMa_surname()); myStamt.setString(4, employee.getEmail()); myStamt.setFloat(5, employee.getSalary()); myStamt.executeUpdate(); } } } ```