commit 4f63b3f5bfed97b50eb5bcd7b87b500b0c2e008d Author: Laura Date: Wed Oct 28 18:09:57 2026 +0100 Actividad 2.1 CRUD tabla Coches en MySQL diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4281832 --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +# Ignorar la carpeta de compilados +bin/ +*.class + +# Ignorar archivos de configuración de Eclipse +.settings/ +.project +.classpath \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..f0fe5f3 --- /dev/null +++ b/pom.xml @@ -0,0 +1,30 @@ + + 4.0.0 + Conectores_01 + Conectores_01 + 0.0.1-SNAPSHOT + + + + + + com.mysql + mysql-connector-j + 26.10.0 + compile + + + + + src + + + maven-compiler-plugin + 3.13.0 + + 26 + + + + + \ No newline at end of file diff --git a/src/org/palomafp/aadd/ljl/AppPrincipalBdMapaMundi.java b/src/org/palomafp/aadd/ljl/AppPrincipalBdMapaMundi.java new file mode 100644 index 0000000..22af41f --- /dev/null +++ b/src/org/palomafp/aadd/ljl/AppPrincipalBdMapaMundi.java @@ -0,0 +1,207 @@ +package org.palomafp.aadd.ljl; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +import org.palomafp.aadd.ljl.model.Coche; + +public class AppPrincipalBdMapaMundi { + + // datos de conexión (sin fichero de configuración) + private static final String DRIVER = "com.mysql.cj.jdbc.Driver"; + private static final String URL = "jdbc:mysql://localhost:3307/concesionario"; + private static final String USUARIO = "root"; + private static final String PASSWORD = "root"; + + // objetos JDBC compartidos por los métodos + private Connection conexion; + private Statement sentencia; + private ResultSet resultado; + + // lista que cargaremos nada más arrancar la aplicación + private List listaInicial = new ArrayList<>(); + + + public static void main(String[] args) { + + AppPrincipalBdMapaMundi app = new AppPrincipalBdMapaMundi(); + Scanner sc = new Scanner(System.in); + + // cargamos todo lo que tiene nuestra base de datos concesionario + app.listaInicial = app.obtenerCoches(); + + int opcion; + + do { + app.menu(); + opcion = sc.nextInt(); + + switch (opcion) { + case 1: + app.listarCoches(); + break; + case 2: + System.out.print("Código del coche a borrar: "); + app.borrarCoche(sc.nextInt()); + break; + case 3: + app.insertarCoches(); + break; + case 4: + app.actualizarCoche(5, "Ibiza Eco"); + break; + case 5: + System.out.println("Saliendo del programa"); + break; + default: + System.out.println("Opción no esperada"); + } + + } while (opcion != 5); + + sc.close(); + } + + + // 0. CARGAR LA BASE DE DATOS INICIAL + private List obtenerCoches() { + + List coches = new ArrayList<>(); + + try { + abrirConexion(); + resultado = sentencia.executeQuery("SELECT * FROM T_COCHE"); + + while (resultado.next()) { + + Coche coche = new Coche(); + coche.setIdentificador(resultado.getInt("identificador")); + coche.setModelo(resultado.getString("modelo")); + coche.setMarca(resultado.getString("marca")); + coche.setCilindrada(resultado.getFloat("cilindrada")); + + coches.add(coche); + } + + } catch (ClassNotFoundException | SQLException e) { + System.out.println("Error: " + e.getMessage()); + + // El finally garantiza que los recursos se cierren si o si -> sin él, un error dejaría la conexión abierta. + } finally { + cerrarConexion(); + } + return coches; + } + + + // 1. CONSULTAR: lee T_COCHEy la imprime + private void listarCoches() { + List coches = obtenerCoches(); + + if (coches.isEmpty()) { + System.out.println("No hay coches en la tabla."); + } + for (Coche c : coches) { + System.out.println(c); + } + } + + + // 2. BORRAR: elimina el coche con el código indicado + private void borrarCoche(int identificador) { + try { + abrirConexion(); + + int filas = sentencia.executeUpdate("DELETE FROM T_COCHE WHERE identificador = " + identificador); + + System.out.println(filas>0 ? "Coche borrado." : "No existe ningún coche con ese código."); + + } catch (ClassNotFoundException | SQLException e) { + System.out.println("Error: " + e.getMessage()); + } finally { + cerrarConexion(); + } + } + + + // 3. INSERTAR: inserta cada coche de la lista inicial (los que ya existen se saltan por clave duplicada) + private void insertarCoches() { + try { + abrirConexion(); + + int insertados = 0; + for (Coche c : listaInicial) { + try { + + sentencia.executeUpdate("INSERT INTO T_COCHE (identificador, modelo, marca, cilindrada) VALUES (" + + c.getIdentificador() + ", '" + c.getModelo() + "', '" + c.getMarca() + "', "+ c.getCilindrada() + ")"); + + insertados++; + + } catch (SQLException e) { + // Clave duplicada: el coche ya está en la tabla + System.out.println("Coche " + c.getIdentificador() + " no insertado: " + e.getMessage()); + } + } + + System.out.println("Coches insertados: " + insertados + " - Coincide con los que has borrado."); + + } catch (ClassNotFoundException | SQLException e) { + System.out.println("Error: " + e.getMessage()); + } finally { + cerrarConexion(); + } + } + + + // 4. ACTUALIZAR: cambia el modelo del coche con el código dado + private void actualizarCoche(int identificador, String nuevoModelo) { + try { + abrirConexion(); + + int filas = sentencia.executeUpdate("UPDATE T_COCHE SET modelo = '" + nuevoModelo + + "' WHERE identificador = " + identificador); + + System.out.println(filas>0 ? "Coche actualizado." : "No existe ningún coche con ese código."); + + } catch (ClassNotFoundException | SQLException e) { + System.out.println("Error: " + e.getMessage()); + } finally { + cerrarConexion(); + } + } + + + + // -------------- MÉTODOS AUXILIARES -------------- + private void menu() { + System.out.println("\n1.Consultar lista de coches \n2.Borrar un coche \n3.Volver a la lista de coches inicial \n4.Actualizar el coche 5 \n5.Salir"); + System.out.print("Introduce una opción: "); + } + + private void abrirConexion() throws ClassNotFoundException, SQLException { + // cargar el driver JDBC -> puede lanzar un ClassNotFoundException + Class.forName(DRIVER); + // crear una conexión con la base de datos + conexion = DriverManager.getConnection(URL, USUARIO, PASSWORD); + // crear un objeto sentencia + sentencia = conexion.createStatement(); + } + + // liberar sentencia y conexión + private void cerrarConexion() { + try { + if (resultado != null) resultado.close(); + if (sentencia != null) sentencia.close(); + if (conexion != null) conexion.close(); + } catch (SQLException e) { + System.out.println("Error al cerrar recursos: " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/org/palomafp/aadd/ljl/model/Coche.java b/src/org/palomafp/aadd/ljl/model/Coche.java new file mode 100644 index 0000000..7f33ee1 --- /dev/null +++ b/src/org/palomafp/aadd/ljl/model/Coche.java @@ -0,0 +1,55 @@ +package org.palomafp.aadd.ljl.model; + +public class Coche { + private int identificador; + private String modelo; + private String marca; + private float cilindrada; + + // constructores + public Coche() { + + } + public Coche(int identificador, String modelo, String marca, float cilindrada) { + super(); + this.identificador = identificador; + this.modelo = modelo; + this.marca = marca; + this.cilindrada = cilindrada; + } + + // getters y setters + public int getIdentificador() { + return identificador; + } + public String getModelo() { + return modelo; + } + public String getMarca() { + return marca; + } + public float getCilindrada() { + return cilindrada; + } + + + public void setIdentificador(int identificador) { + this.identificador = identificador; + } + public void setModelo(String modelo) { + this.modelo = modelo; + } + public void setMarca(String marca) { + this.marca = marca; + } + public void setCilindrada(float cilindrada) { + this.cilindrada = cilindrada; + } + + // sobrescribimos el método toString + @Override + public String toString() { + return "Coche [identificador=" + identificador + ", modelo=" + modelo + ", marca=" + marca + ", cilindrada=" + + cilindrada + "]"; + } +} diff --git a/target/classes/META-INF/MANIFEST.MF b/target/classes/META-INF/MANIFEST.MF new file mode 100644 index 0000000..802a2c6 --- /dev/null +++ b/target/classes/META-INF/MANIFEST.MF @@ -0,0 +1,5 @@ +Manifest-Version: 1.0 +Java-Version: 26 +Build-Jdk-Spec: 25 +Created-By: Maven Integration for Eclipse + diff --git a/target/classes/META-INF/maven/Conectores_01/Conectores_01/pom.properties b/target/classes/META-INF/maven/Conectores_01/Conectores_01/pom.properties new file mode 100644 index 0000000..f951b00 --- /dev/null +++ b/target/classes/META-INF/maven/Conectores_01/Conectores_01/pom.properties @@ -0,0 +1,7 @@ +#Generated by Maven Integration for Eclipse +#Wed Oct 28 18:07:14 CET 2026 +artifactId=Conectores_01 +groupId=Conectores_01 +m2e.projectLocation=C\:\\Users\\lauuj\\Desktop\\DAM\\Segundo curso\\Acceso a datos\\workspaceAD\\Conectores_01 +m2e.projectName=Conectores_01 +version=0.0.1-SNAPSHOT diff --git a/target/classes/META-INF/maven/Conectores_01/Conectores_01/pom.xml b/target/classes/META-INF/maven/Conectores_01/Conectores_01/pom.xml new file mode 100644 index 0000000..f0fe5f3 --- /dev/null +++ b/target/classes/META-INF/maven/Conectores_01/Conectores_01/pom.xml @@ -0,0 +1,30 @@ + + 4.0.0 + Conectores_01 + Conectores_01 + 0.0.1-SNAPSHOT + + + + + + com.mysql + mysql-connector-j + 26.10.0 + compile + + + + + src + + + maven-compiler-plugin + 3.13.0 + + 26 + + + + + \ No newline at end of file