Actividad 2.1 CRUD tabla Coches en MySQL
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
# Ignorar la carpeta de compilados
|
||||
bin/
|
||||
*.class
|
||||
|
||||
# Ignorar archivos de configuración de Eclipse
|
||||
.settings/
|
||||
.project
|
||||
.classpath
|
||||
@@ -0,0 +1,30 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>Conectores_01</groupId>
|
||||
<artifactId>Conectores_01</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<!-- aquí metemos las dependencias que tenga el proyecto -->
|
||||
<dependencies>
|
||||
<!-- Source: https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<version>26.10.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<sourceDirectory>src</sourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<release>26</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -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<Coche> 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<Coche> obtenerCoches() {
|
||||
|
||||
List<Coche> 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<Coche> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 + "]";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
Manifest-Version: 1.0
|
||||
Java-Version: 26
|
||||
Build-Jdk-Spec: 25
|
||||
Created-By: Maven Integration for Eclipse
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,30 @@
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>Conectores_01</groupId>
|
||||
<artifactId>Conectores_01</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<!-- aquí metemos las dependencias que tenga el proyecto -->
|
||||
<dependencies>
|
||||
<!-- Source: https://mvnrepository.com/artifact/com.mysql/mysql-connector-j -->
|
||||
<dependency>
|
||||
<groupId>com.mysql</groupId>
|
||||
<artifactId>mysql-connector-j</artifactId>
|
||||
<version>26.10.0</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<sourceDirectory>src</sourceDirectory>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<configuration>
|
||||
<release>26</release>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
Reference in New Issue
Block a user