Se re escribieron los metodos usando Statement y executeUpdate
This commit is contained in:
@@ -6,6 +6,11 @@ import java.sql.PreparedStatement;
|
|||||||
import java.sql.ResultSet;
|
import java.sql.ResultSet;
|
||||||
import java.sql.SQLException;
|
import java.sql.SQLException;
|
||||||
import java.sql.Statement;
|
import java.sql.Statement;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
import org.palomafp.aadd.jaec.model.Coche;
|
||||||
|
|
||||||
public class AppPrincipal {
|
public class AppPrincipal {
|
||||||
|
|
||||||
@@ -14,84 +19,159 @@ public class AppPrincipal {
|
|||||||
private static final String USER = "root";
|
private static final String USER = "root";
|
||||||
private static final String PASSWORD = "a123";
|
private static final String PASSWORD = "a123";
|
||||||
|
|
||||||
|
Connection conexion = null;
|
||||||
|
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
try (Connection con = DriverManager.getConnection(URL, USER, PASSWORD)) {
|
AppPrincipal app = new AppPrincipal();
|
||||||
System.out.println("--- 1. CONSULTAR LA LISTA DE COCHES ---");
|
|
||||||
consultarCoches(con);
|
|
||||||
|
|
||||||
System.out.println("\n--- 2. ACTUALIZAR EL COCHE CON CÓDIGO 5 (Ibiza Eco) ---");
|
try {
|
||||||
actualizarCoche(con, 5, "Ibiza Eco");
|
// Inicializa recursos que se usarán.
|
||||||
consultarCoches(con); // Ver el cambio
|
// Se abre la conexion entre Java y la BBDD MySQL
|
||||||
|
app.inicializarRecursos();
|
||||||
|
|
||||||
System.out.println("\n--- 3. BORRAR REGISTROS ---");
|
// 1. Obtener lista Coches
|
||||||
borrarCoche(con, 7); // Ejemplo borrando el coche 7
|
List<Coche> listaCoches = app.obtenerListaCoches();
|
||||||
consultarCoches(con);
|
System.out.println(listaCoches);
|
||||||
|
|
||||||
System.out.println("\n--- 4. INSERTAR UN COCHE NUEVO ---");
|
// 2.1 Borrar un Coche con identificador = 3
|
||||||
insertarCoche(con, 8, "Seat", "Arona", 1.0);
|
app.borrarCoche(3);
|
||||||
consultarCoches(con);
|
|
||||||
|
|
||||||
} catch (SQLException e) {
|
// 2.2 Borrar TODOS los Coches
|
||||||
System.out.println("Error de base de datos:");
|
app.borrarCoches();
|
||||||
|
|
||||||
|
// 3. Insertar Coches
|
||||||
|
app.insertarCoches(listaCoches);
|
||||||
|
|
||||||
|
// 4. Actualizar Coche
|
||||||
|
app.actualizarCoche(5, "Ibiza Eco");
|
||||||
|
|
||||||
|
} finally {
|
||||||
|
// Cerrar la recursos.
|
||||||
|
// Se cierra la conexion entre Java y la BBDD MySQL
|
||||||
|
app.cerrarRecursos();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Se inicia la conexion. Usamos las constantes de URL, USER y PASSWORD
|
||||||
|
private void inicializarRecursos() {
|
||||||
|
try {
|
||||||
|
Class.forName("com.mysql.cj.jdbc.Driver");
|
||||||
|
conexion = DriverManager.getConnection(URL, USER, PASSWORD);
|
||||||
|
} catch (ClassNotFoundException | SQLException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Método para consultar e imprimir la lista de coches (Read)
|
// Se cierra la conexion
|
||||||
public static void consultarCoches(Connection con) {
|
private void cerrarRecursos() {
|
||||||
String sql = "SELECT identificador, marca, modelo, cilindrada FROM T_COCHE";
|
if (conexion != null) {
|
||||||
try (Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery(sql)) {
|
try {
|
||||||
|
conexion.close();
|
||||||
|
} catch (SQLException e) {
|
||||||
|
System.err.println("Error al cerrar la conexión: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
while (rs.next()) {
|
// SELECT
|
||||||
int id = rs.getInt("identificador");
|
// Metodo para obtener una Lista de objetos Coche
|
||||||
String marca = rs.getString("marca");
|
private List<Coche> obtenerListaCoches() {
|
||||||
String modelo = rs.getString("modelo");
|
List<Coche> listaCoches = new ArrayList<Coche>();
|
||||||
double cilindrada = rs.getDouble("cilindrada");
|
|
||||||
|
|
||||||
System.out.println("ID: " + id + " | " + marca + " " + modelo + " | Cilindrada: " + cilindrada);
|
String sentenciaSQL = "SELECT * FROM T_COCHE";
|
||||||
|
try (Statement sentencia = conexion.createStatement();
|
||||||
|
ResultSet resultados = sentencia.executeQuery(sentenciaSQL);) {
|
||||||
|
while (resultados.next()) {
|
||||||
|
int identificador = resultados.getInt("identificador");
|
||||||
|
String marca = resultados.getString("marca");
|
||||||
|
String modelo = resultados.getString("modelo");
|
||||||
|
float cilindrada = resultados.getFloat("cilindrada");
|
||||||
|
|
||||||
|
Coche coche = new Coche();
|
||||||
|
coche.setIdentificador(identificador);
|
||||||
|
coche.setMarca(marca);
|
||||||
|
coche.setModelo(modelo);
|
||||||
|
coche.setCilindrada(cilindrada);
|
||||||
|
|
||||||
|
listaCoches.add(coche);
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
return listaCoches;
|
||||||
|
}
|
||||||
|
|
||||||
|
// INSERT
|
||||||
|
// Metodo para insertar un Coche en la base de datos
|
||||||
|
// sentencia.executeUpdate() para instrucciones INSERT, UPDATE, DELETE o
|
||||||
|
// CREATE TABLE
|
||||||
|
// sentencia.executeUpdate() devuelve un int igual a numero de filas afectadas
|
||||||
|
// sentencia.execute() devuelve boolean (TRUE en caso de consultas SELECT,
|
||||||
|
// FALSE en caso de INSERT, UPDATE o DELETE)
|
||||||
|
private void insertarCoches(List<Coche> listaCoches) {
|
||||||
|
// Le paso como parametro una lista de objetos Coche
|
||||||
|
String sentenciaSQL = "INSERT INTO T_COCHE (identificador, marca, modelo, cilindrada) VALUES (%d, '%s', '%s', %.2f)";
|
||||||
|
try (Statement sentencia = conexion.createStatement();) {
|
||||||
|
for (Coche coche : listaCoches) {
|
||||||
|
String sentenciaSQLRellena = String.format(Locale.US, sentenciaSQL, coche.getIdentificador(),
|
||||||
|
coche.getMarca(), coche.getModelo(), coche.getCilindrada());
|
||||||
|
sentencia.executeUpdate(sentenciaSQLRellena);
|
||||||
|
System.out.println(sentenciaSQLRellena);
|
||||||
}
|
}
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Método para actualizar el modelo del coche con código 5 (Update)
|
// DELETE TODOS
|
||||||
public static void actualizarCoche(Connection con, int id, String nuevoModelo) {
|
// Metodo para borrar TODOS LOS COCHES de la base de datos usand
|
||||||
String sql = "UPDATE T_COCHE SET modelo = ? WHERE identificador = ?";
|
private void borrarCoches() {
|
||||||
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
|
String sentenciaSQL = "DELETE FROM T_COCHE";
|
||||||
pstmt.setString(1, nuevoModelo);
|
|
||||||
pstmt.setInt(2, id);
|
try (Statement sentencia = conexion.createStatement();) {
|
||||||
int filas = pstmt.executeUpdate();
|
sentencia.executeUpdate(sentenciaSQL);
|
||||||
System.out.println("Coche actualizado con éxito. Filas afectadas: " + filas);
|
System.out.println(sentenciaSQL);
|
||||||
|
} catch (SQLException e) {
|
||||||
|
// TODO Auto-generated catch block
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
// DELETE
|
||||||
|
// Método para borrar UN SOLO COCHE usando su identificador
|
||||||
|
private void borrarCoche(int idCoche) {
|
||||||
|
String sentenciaSQL = "DELETE FROM T_COCHE WHERE identificador = %d";
|
||||||
|
|
||||||
|
try (Statement sentencia = conexion.createStatement()) {
|
||||||
|
sentenciaSQL = String.format(sentenciaSQL, idCoche);
|
||||||
|
|
||||||
|
// Para sentencias de modificación (INSERT, UPDATE, DELETE) se usa executeUpdate
|
||||||
|
int filasAfectadas = sentencia.executeUpdate(sentenciaSQL);
|
||||||
|
|
||||||
|
System.out.println(sentenciaSQL);
|
||||||
|
System.out.println("Coches borrados: " + filasAfectadas);
|
||||||
|
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Método para borrar un coche por su identificador (Delete)
|
// UPDATE
|
||||||
public static void borrarCoche(Connection con, int id) {
|
// Metodo para actualizar el modelo de un coche usando su identificador
|
||||||
String sql = "DELETE FROM T_COCHE WHERE identificador = ?";
|
private void actualizarCoche(int idCoche, String modelo) {
|
||||||
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
|
String sentenciaSQL = "UPDATE T_COCHE SET modelo = '%s' WHERE identificador = %d";
|
||||||
pstmt.setInt(1, id);
|
|
||||||
int filas = pstmt.executeUpdate();
|
try (Statement sentencia = conexion.createStatement();) {
|
||||||
System.out.println("Coche con ID " + id + " borrado. Filas afectadas: " + filas);
|
sentenciaSQL = String.format(sentenciaSQL, modelo, idCoche);
|
||||||
|
sentencia.executeUpdate(sentenciaSQL);
|
||||||
|
System.out.println(sentenciaSQL);
|
||||||
} catch (SQLException e) {
|
} catch (SQLException e) {
|
||||||
e.printStackTrace();
|
System.err.println(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Método para insertar un coche (Create)
|
|
||||||
public static void insertarCoche(Connection con, int id, String marca, String modelo, double cilindrada) {
|
|
||||||
String sql = "INSERT INTO T_COCHE (identificador, marca, modelo, cilindrada) VALUES (?, ?, ?, ?)";
|
|
||||||
try (PreparedStatement pstmt = con.prepareStatement(sql)) {
|
|
||||||
pstmt.setInt(1, id);
|
|
||||||
pstmt.setString(2, marca);
|
|
||||||
pstmt.setString(3, modelo);
|
|
||||||
pstmt.setDouble(4, cilindrada);
|
|
||||||
pstmt.executeUpdate();
|
|
||||||
System.out.println("Coche insertado correctamente.");
|
|
||||||
} catch (SQLException e) {
|
|
||||||
e.printStackTrace();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user