diff --git a/db_config.properties b/db_config.properties
new file mode 100644
index 0000000..f2411ee
--- /dev/null
+++ b/db_config.properties
@@ -0,0 +1,6 @@
+#db.servidor=172.18.185.243
+db.servidor=debianpsp
+db.baseDatos=tienda
+db.usuario=root
+db.clave=example
+
diff --git a/mibd.db b/mibd.db
new file mode 100644
index 0000000..e69de29
diff --git a/pom.xml b/pom.xml
index 8da762a..d58bc29 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,5 +1,5 @@
-
+
4.0.0
iesthiar
t14ejemplos
@@ -20,6 +20,25 @@
javafx-fxml
21
+
+
+ mysql
+ mysql-connector-java
+ 8.0.33
+
+
+
+
+ org.apache.commons
+ commons-dbcp2
+ 2.12.0
+
+
+
+ org.xerial
+ sqlite-jdbc
+ 3.45.3.0
+
@@ -48,4 +67,4 @@
-
+
\ No newline at end of file
diff --git a/src/main/java/iesthiar/App.java b/src/main/java/iesthiar/App.java
index f58aa40..4348807 100644
--- a/src/main/java/iesthiar/App.java
+++ b/src/main/java/iesthiar/App.java
@@ -1,13 +1,13 @@
package iesthiar;
+import java.io.IOException;
+
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
-import java.io.IOException;
-
/**
* JavaFX App
*/
@@ -17,7 +17,7 @@ public class App extends Application {
@Override
public void start(Stage stage) throws IOException {
- scene = new Scene(loadFXML("primary"), 640, 480);
+ scene = new Scene(loadFXML("pruebaConexion"), 640, 480);
stage.setScene(scene);
stage.show();
}
diff --git a/src/main/java/iesthiar/EjemploSQLite.java b/src/main/java/iesthiar/EjemploSQLite.java
new file mode 100644
index 0000000..377a6ff
--- /dev/null
+++ b/src/main/java/iesthiar/EjemploSQLite.java
@@ -0,0 +1,36 @@
+package iesthiar;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+
+public class EjemploSQLite {
+ public static void main(String[] args) {
+ try (Connection c = DriverManager.getConnection("jdbc:sqlite:mibd.db");
+ PreparedStatement pstm=c.prepareStatement("SELECT name FROM sqlite_master WHERE type='table' AND name='cliente';");
+ ) {
+ System.out.println("Base de datos conectada");
+ // Crear las tablas si es necesario
+ try (ResultSet rs=pstm.executeQuery()){
+ if (rs.next()){
+ System.out.println("Existe");
+ }
+ else {
+ System.out.println("No existe");
+ pstm=c.prepareStatement("create table cliente(
+
+ )");
+ }
+
+ } catch (Exception e){
+ System.out.println("Error en la consulta");
+ }
+
+ } catch (Exception e) {
+ System.out.println("Error al entrar en la BD");
+ e.printStackTrace();
+ }
+
+ }
+}
diff --git a/src/main/java/iesthiar/PreparadasController.java b/src/main/java/iesthiar/PreparadasController.java
new file mode 100644
index 0000000..1e2cd72
--- /dev/null
+++ b/src/main/java/iesthiar/PreparadasController.java
@@ -0,0 +1,40 @@
+package iesthiar;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import javafx.fxml.FXML;
+import javafx.scene.control.TextArea;
+import javafx.scene.control.TextField;
+
+public class PreparadasController {
+ @FXML
+ private TextArea salida;
+ @FXML
+ private TextField nombre;
+
+ @FXML
+ private void conectar() throws IOException {
+ String url = "jdbc:mysql://172.18.185.243:3306/tienda";
+ String sentenciasql = "select * from clientes where nombre=?";
+ try (Connection conn = DriverManager.getConnection(url, "root", "example");
+ PreparedStatement preparada=conn.prepareStatement(sentenciasql);) {
+ preparada.setString(1, nombre.getText());
+ try (ResultSet res=preparada.executeQuery()) {
+ while (res.next()){
+ salida.appendText(res.getInt(1)+":"+res.getString(2)+" - "+res.getString(3)+"\n");
+ }
+ } catch (Exception e) {
+ salida.appendText("Error en la consulta");
+ }
+ salida.appendText("Conexión establecida ");
+ } catch (SQLException e) {
+ salida.appendText("Error en la conexión a la base de datos");
+ }
+ }
+
+}
diff --git a/src/main/java/iesthiar/PrimaryController.java b/src/main/java/iesthiar/PrimaryController.java
deleted file mode 100644
index 3d351a4..0000000
--- a/src/main/java/iesthiar/PrimaryController.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package iesthiar;
-
-import java.io.IOException;
-import javafx.fxml.FXML;
-
-public class PrimaryController {
-
- @FXML
- private void switchToSecondary() throws IOException {
- App.setRoot("secondary");
- }
-}
diff --git a/src/main/java/iesthiar/PruebaConexionController.java b/src/main/java/iesthiar/PruebaConexionController.java
new file mode 100644
index 0000000..6ce0b45
--- /dev/null
+++ b/src/main/java/iesthiar/PruebaConexionController.java
@@ -0,0 +1,95 @@
+package iesthiar;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Optional;
+
+import javafx.fxml.FXML;
+import javafx.scene.control.TextArea;
+import javafx.scene.control.TextField;
+import javafx.scene.control.TextInputDialog;
+
+public class PruebaConexionController {
+ @FXML
+ private TextArea salida;
+ @FXML
+ private TextArea salidaRes;
+ @FXML
+ private TextArea salidaRes3;
+
+ @FXML
+ private TextField servidor;
+ @FXML
+ private TextField puerto;
+ @FXML
+ private TextField baseDatos;
+ @FXML
+ private TextField usuario;
+ @FXML
+ private TextField nombre;
+
+
+ @FXML
+ private void conectar() throws IOException {
+ String url = "jdbc:mysql://localhost:3306/tienda";
+ // String sentenciasql = "select * from clientes";
+ try (Connection conn = DriverManager.getConnection(url, "root", "example");) {
+ salida.appendText("Conexión establecida ");
+ } catch (SQLException e) {
+ salida.appendText("Error en la conexión a la base de datos");
+ }
+ }
+
+ @FXML
+ private void conectarRes() throws IOException {
+ String url = "jdbc:mysql://" + servidor.getText() + ":" + puerto.getText() + "/" + baseDatos.getText();
+ String sentenciasql = "select * from clientes";
+ try (Connection conn = DriverManager.getConnection(url, usuario.getText(), pideClave());
+ Statement st = conn.createStatement();
+ ResultSet rs = st.executeQuery(sentenciasql)) {
+ salidaRes.appendText("Conexión establecida \n");
+ while (rs.next()) {
+ salidaRes.appendText("Id: " + rs.getInt(1) + " Nombre: " + rs.getString("nombre") + " Dirección: "
+ + rs.getString(3) + "\n");
+ }
+ } catch (SQLException e) {
+ salidaRes.appendText("Error en la conexión a la base de datos");
+ }
+ }
+
+ private String pideClave() {
+ TextInputDialog pregunta = new TextInputDialog();
+ pregunta.setTitle("Conexión a la BD");
+ pregunta.setHeaderText("Conexión a "+baseDatos.getText()+" en "+servidor.getText());
+ pregunta.setContentText("Introduce la clave del usuario "+usuario.getText());
+
+ // Traditional way to get the response value.
+ Optional result = pregunta.showAndWait();
+ if (result.isPresent()) {
+ return result.get();
+ } else return "";
+ }
+
+ @FXML
+ private void conectarRes3() throws IOException {
+ String url = "jdbc:mysql://172.18.185.243:3306/tienda";
+ // ' or 1=1 or nombre='
+ // ' or ''='
+ String sentenciasql = "select * from clientes where nombre ='"+nombre.getText()+"'";
+ try (Connection conn = DriverManager.getConnection(url, "root", "example");
+ Statement st = conn.createStatement();
+ ResultSet rs = st.executeQuery(sentenciasql)) {
+ salidaRes3.appendText("Conexión establecida \n");
+ while (rs.next()) {
+ salidaRes3.appendText("Id: " + rs.getInt(1) + " Nombre: " + rs.getString("nombre") + " Dirección: "
+ + rs.getString(3) + "\n");
+ }
+ } catch (SQLException e) {
+ salidaRes3.appendText("Error en la conexión a la base de datos");
+ }
+ }
+}
diff --git a/src/main/java/iesthiar/SecondaryController.java b/src/main/java/iesthiar/SecondaryController.java
deleted file mode 100644
index cdb14da..0000000
--- a/src/main/java/iesthiar/SecondaryController.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package iesthiar;
-
-import java.io.IOException;
-import javafx.fxml.FXML;
-
-public class SecondaryController {
-
- @FXML
- private void switchToPrimary() throws IOException {
- App.setRoot("primary");
- }
-}
\ No newline at end of file
diff --git a/src/main/java/iesthiar/_49_EjemploCompleto.java b/src/main/java/iesthiar/_49_EjemploCompleto.java
new file mode 100644
index 0000000..043fcb6
--- /dev/null
+++ b/src/main/java/iesthiar/_49_EjemploCompleto.java
@@ -0,0 +1,27 @@
+package iesthiar;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+
+public class _49_EjemploCompleto {
+ public static void main(String[] args) {
+ String url = "jdbc:mysql://localhost:3306/tienda";
+ String sentenciasql = "select * from clientes";
+ try (Connection conn = DriverManager.getConnection(url, "root", "example");
+ Statement st = conn.createStatement();
+ ResultSet rs = st.executeQuery(sentenciasql)) {
+ System.out.println("Conexión establecida ");
+ while (rs.next()) {
+ System.out.print("Id: " + rs.getInt(1));
+ System.out.print(" Nombre: " + rs.getString("nombre"));
+ System.out.println(" Dirección: " + rs.getString(3));
+ }
+ } catch (SQLException e) {
+ System.err.println("Error en la conexión a la base de datos");
+ }
+ }
+}
diff --git a/src/main/java/iesthiar/gestorClientes/DBManager.java b/src/main/java/iesthiar/gestorClientes/DBManager.java
new file mode 100644
index 0000000..61066a8
--- /dev/null
+++ b/src/main/java/iesthiar/gestorClientes/DBManager.java
@@ -0,0 +1,359 @@
+package iesthiar.gestorClientes;
+
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+/**
+ *
+ * @author lionel
+ */
+public class DBManager {
+
+ // Conexión a la base de datos
+ private static Connection conn = null;
+
+ // Configuración de la conexión a la base de datos
+ private static final String DB_HOST = "localhost";
+ private static final String DB_PORT = "3306";
+ private static final String DB_NAME = "tienda";
+ private static final String DB_URL = "jdbc:mysql://" + DB_HOST + ":" + DB_PORT + "/" + DB_NAME + "?serverTimezone=UTC";
+ private static final String DB_USER = "root";
+ private static final String DB_PASS = "";
+ private static final String DB_MSQ_CONN_OK = "CONEXIÓN CORRECTA";
+ private static final String DB_MSQ_CONN_NO = "ERROR EN LA CONEXIÓN";
+
+ // Configuración de la tabla Clientes
+ private static final String DB_CLI = "clientes";
+ private static final String DB_CLI_SELECT = "SELECT * FROM " + DB_CLI;
+ private static final String DB_CLI_ID = "id";
+ private static final String DB_CLI_NOM = "nombre";
+ private static final String DB_CLI_DIR = "direccion";
+
+ //////////////////////////////////////////////////
+ // MÉTODOS DE CONEXIÓN A LA BASE DE DATOS
+ //////////////////////////////////////////////////
+ ;
+
+ /**
+ * Intenta cargar el JDBC driver.
+ * @return true si pudo cargar el driver, false en caso contrario
+ */
+ public static boolean loadDriver() {
+ try {
+ System.out.print("Cargando Driver...");
+ Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
+ System.out.println("OK!");
+ return true;
+ } catch (ClassNotFoundException ex) {
+ ex.printStackTrace();
+ return false;
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ return false;
+ }
+ }
+
+ /**
+ * Intenta conectar con la base de datos.
+ *
+ * @return true si pudo conectarse, false en caso contrario
+ */
+ public static boolean connect() {
+ try {
+ System.out.print("Conectando a la base de datos...");
+ conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
+ System.out.println("OK!");
+ return true;
+ } catch (SQLException ex) {
+ ex.printStackTrace();
+ return false;
+ }
+ }
+
+ /**
+ * Comprueba la conexión y muestra su estado por pantalla
+ *
+ * @return true si la conexión existe y es válida, false en caso contrario
+ */
+ public static boolean isConnected() {
+ // Comprobamos estado de la conexión
+ try {
+ if (conn != null && conn.isValid(0)) {
+ System.out.println(DB_MSQ_CONN_OK);
+ return true;
+ } else {
+ return false;
+ }
+ } catch (SQLException ex) {
+ System.out.println(DB_MSQ_CONN_NO);
+ ex.printStackTrace();
+ return false;
+ }
+ }
+
+ /**
+ * Cierra la conexión con la base de datos
+ */
+ public static void close() {
+ try {
+ System.out.print("Cerrando la conexión...");
+ conn.close();
+ System.out.println("OK!");
+ } catch (SQLException ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ //////////////////////////////////////////////////
+ // MÉTODOS DE TABLA CLIENTES
+ //////////////////////////////////////////////////
+ ;
+
+ // Devuelve
+ // Los argumentos indican el tipo de ResultSet deseado
+ /**
+ * Obtiene toda la tabla clientes de la base de datos
+ * @param resultSetType Tipo de ResultSet
+ * @param resultSetConcurrency Concurrencia del ResultSet
+ * @return ResultSet (del tipo indicado) con la tabla, null en caso de error
+ */
+ public static ResultSet getTablaClientes(int resultSetType, int resultSetConcurrency) {
+ try {
+ Statement stmt = conn.createStatement(resultSetType, resultSetConcurrency);
+ ResultSet rs = stmt.executeQuery(DB_CLI_SELECT);
+ //stmt.close();
+ return rs;
+ } catch (SQLException ex) {
+ ex.printStackTrace();
+ return null;
+ }
+
+ }
+
+ /**
+ * Obtiene toda la tabla clientes de la base de datos
+ *
+ * @return ResultSet (por defecto) con la tabla, null en caso de error
+ */
+ public static ResultSet getTablaClientes() {
+ return getTablaClientes(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+ }
+
+ /**
+ * Imprime por pantalla el contenido de la tabla clientes
+ */
+ public static void printTablaClientes() {
+ try {
+ ResultSet rs = getTablaClientes(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+ while (rs.next()) {
+ int id = rs.getInt(DB_CLI_ID);
+ String n = rs.getString(DB_CLI_NOM);
+ String d = rs.getString(DB_CLI_DIR);
+ System.out.println(id + "\t" + n + "\t" + d);
+ }
+ rs.close();
+ } catch (SQLException ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ //////////////////////////////////////////////////
+ // MÉTODOS DE UN SOLO CLIENTE
+ //////////////////////////////////////////////////
+ ;
+
+ /**
+ * Solicita a la BD el cliente con id indicado
+ * @param id id del cliente
+ * @return ResultSet con el resultado de la consulta, null en caso de error
+ */
+ public static ResultSet getCliente(int id) {
+ try {
+ // Realizamos la consulta SQL
+ Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
+ String sql = DB_CLI_SELECT + " WHERE " + DB_CLI_ID + "='" + id + "';";
+ //System.out.println(sql);
+ ResultSet rs = stmt.executeQuery(sql);
+ //stmt.close();
+
+ // Si no hay primer registro entonces no existe el cliente
+ if (!rs.first()) {
+ return null;
+ }
+
+ // Todo bien, devolvemos el cliente
+ return rs;
+
+ } catch (SQLException ex) {
+ ex.printStackTrace();
+ return null;
+ }
+ }
+
+ /**
+ * Comprueba si en la BD existe el cliente con id indicado
+ *
+ * @param id id del cliente
+ * @return verdadero si existe, false en caso contrario
+ */
+ public static boolean existsCliente(int id) {
+ try {
+ // Obtenemos el cliente
+ ResultSet rs = getCliente(id);
+
+ // Si rs es null, se ha producido un error
+ if (rs == null) {
+ return false;
+ }
+
+ // Si no existe primer registro
+ if (!rs.first()) {
+ rs.close();
+ return false;
+ }
+
+ // Todo bien, existe el cliente
+ rs.close();
+ return true;
+
+ } catch (SQLException ex) {
+ ex.printStackTrace();
+ return false;
+ }
+ }
+
+ /**
+ * Imprime los datos del cliente con id indicado
+ *
+ * @param id id del cliente
+ */
+ public static void printCliente(int id) {
+ try {
+ // Obtenemos el cliente
+ ResultSet rs = getCliente(id);
+ if (rs == null || !rs.first()) {
+ System.out.println("Cliente " + id + " NO EXISTE");
+ return;
+ }
+
+ // Imprimimos su información por pantalla
+ int cid = rs.getInt(DB_CLI_ID);
+ String nombre = rs.getString(DB_CLI_NOM);
+ String direccion = rs.getString(DB_CLI_DIR);
+ System.out.println("Cliente " + cid + "\t" + nombre + "\t" + direccion);
+
+ } catch (SQLException ex) {
+ System.out.println("Error al solicitar cliente " + id);
+ ex.printStackTrace();
+ }
+ }
+
+ /**
+ * Solicita a la BD insertar un nuevo registro cliente
+ *
+ * @param nombre nombre del cliente
+ * @param direccion dirección del cliente
+ * @return verdadero si pudo insertarlo, false en caso contrario
+ */
+ public static boolean insertCliente(String nombre, String direccion) {
+ try {
+ // Obtenemos la tabla clientes
+ System.out.print("Insertando cliente " + nombre + "...");
+ ResultSet rs = getTablaClientes(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
+
+ // Insertamos el nuevo registro
+ rs.moveToInsertRow();
+ rs.updateString(DB_CLI_NOM, nombre);
+ rs.updateString(DB_CLI_DIR, direccion);
+ rs.insertRow();
+
+ // Todo bien, cerramos ResultSet y devolvemos true
+ rs.close();
+ System.out.println("OK!");
+ return true;
+
+ } catch (SQLException ex) {
+ ex.printStackTrace();
+ return false;
+ }
+ }
+
+ /**
+ * Solicita a la BD modificar los datos de un cliente
+ *
+ * @param id id del cliente a modificar
+ * @param nombre nuevo nombre del cliente
+ * @param direccion nueva dirección del cliente
+ * @return verdadero si pudo modificarlo, false en caso contrario
+ */
+ public static boolean updateCliente(int id, String nuevoNombre, String nuevaDireccion) {
+ try {
+ // Obtenemos el cliente
+ System.out.print("Actualizando cliente " + id + "... ");
+ ResultSet rs = getCliente(id);
+
+ // Si no existe el Resultset
+ if (rs == null) {
+ System.out.println("Error. ResultSet null.");
+ return false;
+ }
+
+ // Si tiene un primer registro, lo eliminamos
+ if (rs.first()) {
+ rs.updateString(DB_CLI_NOM, nuevoNombre);
+ rs.updateString(DB_CLI_DIR, nuevaDireccion);
+ rs.updateRow();
+ rs.close();
+ System.out.println("OK!");
+ return true;
+ } else {
+ System.out.println("ERROR. ResultSet vacío.");
+ return false;
+ }
+ } catch (SQLException ex) {
+ ex.printStackTrace();
+ return false;
+ }
+ }
+
+ /**
+ * Solicita a la BD eliminar un cliente
+ *
+ * @param id id del cliente a eliminar
+ * @return verdadero si pudo eliminarlo, false en caso contrario
+ */
+ public static boolean deleteCliente(int id) {
+ try {
+ System.out.print("Eliminando cliente " + id + "... ");
+
+ // Obtenemos el cliente
+ ResultSet rs = getCliente(id);
+
+ // Si no existe el Resultset
+ if (rs == null) {
+ System.out.println("ERROR. ResultSet null.");
+ return false;
+ }
+
+ // Si existe y tiene primer registro, lo eliminamos
+ if (rs.first()) {
+ rs.deleteRow();
+ rs.close();
+ System.out.println("OK!");
+ return true;
+ } else {
+ System.out.println("ERROR. ResultSet vacío.");
+ return false;
+ }
+
+ } catch (SQLException ex) {
+ ex.printStackTrace();
+ return false;
+ }
+ }
+
+}
diff --git a/src/main/java/iesthiar/gestorClientes/GestionClientes.java b/src/main/java/iesthiar/gestorClientes/GestionClientes.java
new file mode 100644
index 0000000..e08f95b
--- /dev/null
+++ b/src/main/java/iesthiar/gestorClientes/GestionClientes.java
@@ -0,0 +1,159 @@
+package iesthiar.gestorClientes;
+
+
+import java.util.Scanner;
+
+/**
+ *
+ * @author lionel
+ */
+public class GestionClientes {
+
+ public static void main(String[] args) {
+
+ DBManager.loadDriver();
+ DBManager.connect();
+
+ boolean salir = false;
+ do {
+ salir = menuPrincipal();
+ } while (!salir);
+
+ DBManager.close();
+
+ }
+
+ public static boolean menuPrincipal() {
+ System.out.println("");
+ System.out.println("MENU PRINCIPAL");
+ System.out.println("1. Listar clientes");
+ System.out.println("2. Nuevo cliente");
+ System.out.println("3. Modificar cliente");
+ System.out.println("4. Eliminar cliente");
+ System.out.println("5. Salir");
+
+ Scanner in = new Scanner(System.in);
+
+ int opcion = pideInt("Elige una opción: ");
+
+ switch (opcion) {
+ case 1:
+ opcionMostrarClientes();
+ return false;
+ case 2:
+ opcionNuevoCliente();
+ return false;
+ case 3:
+ opcionModificarCliente();
+ return false;
+ case 4:
+ opcionEliminarCliente();
+ return false;
+ case 5:
+ return true;
+ default:
+ System.out.println("Opción elegida incorrecta");
+ return false;
+ }
+
+ }
+
+ public static int pideInt(String mensaje){
+
+ while(true) {
+ try {
+ System.out.print(mensaje);
+ Scanner in = new Scanner(System.in);
+ int valor = in.nextInt();
+ //in.nextLine();
+ return valor;
+ } catch (Exception e) {
+ System.out.println("No has introducido un número entero. Vuelve a intentarlo.");
+ }
+ }
+ }
+
+ public static String pideLinea(String mensaje){
+
+ while(true) {
+ try {
+ System.out.print(mensaje);
+ Scanner in = new Scanner(System.in);
+ String linea = in.nextLine();
+ return linea;
+ } catch (Exception e) {
+ System.out.println("No has introducido una cadena de texto. Vuelve a intentarlo.");
+ }
+ }
+ }
+
+ public static void opcionMostrarClientes() {
+ System.out.println("Listado de Clientes:");
+ DBManager.printTablaClientes();
+ }
+
+ public static void opcionNuevoCliente() {
+ Scanner in = new Scanner(System.in);
+
+ System.out.println("Introduce los datos del nuevo cliente:");
+ String nombre = pideLinea("Nombre: ");
+ String direccion = pideLinea("Dirección: ");
+
+ boolean res = DBManager.insertCliente(nombre, direccion);
+
+ if (res) {
+ System.out.println("Cliente registrado correctamente");
+ } else {
+ System.out.println("Error :(");
+ }
+ }
+
+ public static void opcionModificarCliente() {
+ Scanner in = new Scanner(System.in);
+
+ int id = pideInt("Indica el id del cliente a modificar: ");
+
+ // Comprobamos si existe el cliente
+ if (!DBManager.existsCliente(id)) {
+ System.out.println("El cliente " + id + " no existe.");
+ return;
+ }
+
+ // Mostramos datos del cliente a modificar
+ DBManager.printCliente(id);
+
+ // Solicitamos los nuevos datos
+ String nombre = pideLinea("Nuevo nombre: ");
+ String direccion = pideLinea("Nueva dirección: ");
+
+ // Registramos los cambios
+ boolean res = DBManager.updateCliente(id, nombre, direccion);
+
+ if (res) {
+ System.out.println("Cliente modificado correctamente");
+ } else {
+ System.out.println("Error :(");
+ }
+ }
+
+ public static void opcionEliminarCliente() {
+ Scanner in = new Scanner(System.in);
+
+ int id = pideInt("Indica el id del cliente a eliminar: ");
+
+ // Comprobamos si existe el cliente
+ if (!DBManager.existsCliente(id)) {
+ System.out.println("El cliente " + id + " no existe.");
+ return;
+ }
+
+ // Eliminamos el cliente
+ boolean res = DBManager.deleteCliente(id);
+
+ if (res) {
+ System.out.println("Cliente eliminado correctamente");
+ } else {
+ System.out.println("Error :(");
+ }
+ }
+}
diff --git a/src/main/java/iesthiar/gestorClientes/GestionClientesIGU.java b/src/main/java/iesthiar/gestorClientes/GestionClientesIGU.java
new file mode 100644
index 0000000..abf7b65
--- /dev/null
+++ b/src/main/java/iesthiar/gestorClientes/GestionClientesIGU.java
@@ -0,0 +1,744 @@
+package iesthiar.gestorClientes;
+
+
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import javax.swing.JOptionPane;
+
+public class GestionClientesIGU extends javax.swing.JFrame {
+
+ private ResultSet rsClientes;
+ private boolean clienteValido = false;
+
+ public GestionClientesIGU() {
+
+ // Inicilización de componentes gráficos
+ initComponents();
+
+ // Cargamos driver y conectamos con la BD
+ DBManager.loadDriver();
+ DBManager.connect();
+
+ // Obtenemos el ResultSet de clientes y mostramos el primero
+ obtenerClientes();
+ muestraClientePrimero();
+ }
+
+ /**
+ * This method is called from within the constructor to initialize the form.
+ * WARNING: Do NOT modify this code. The content of this method is always
+ * regenerated by the Form Editor.
+ */
+ @SuppressWarnings("unchecked")
+ // //GEN-BEGIN:initComponents
+ private void initComponents() {
+
+ jfNuevoCliente = new javax.swing.JFrame();
+ lblVNCTitulo = new javax.swing.JLabel();
+ jpVNC = new javax.swing.JPanel();
+ lblVNCNombre = new javax.swing.JLabel();
+ txtVNCNombre = new javax.swing.JTextField();
+ lblVNCDireccion = new javax.swing.JLabel();
+ txtVNCDireccion = new javax.swing.JTextField();
+ btnVNCAceptar = new javax.swing.JButton();
+ btnVNCCancelar = new javax.swing.JButton();
+ jfEditarCliente = new javax.swing.JFrame();
+ lblVECTitulo = new javax.swing.JLabel();
+ jpVEC = new javax.swing.JPanel();
+ lblVECId = new javax.swing.JLabel();
+ lblVECIdCliente = new javax.swing.JLabel();
+ lblVECNombre = new javax.swing.JLabel();
+ txtVECNombre = new javax.swing.JTextField();
+ lblVECDireccion = new javax.swing.JLabel();
+ txtVECDireccion = new javax.swing.JTextField();
+ btnVECAceptar = new javax.swing.JButton();
+ btnVECCancelar = new javax.swing.JButton();
+ jPanelVP = new javax.swing.JPanel();
+ lblTitulo = new javax.swing.JLabel();
+ btnPrimero = new javax.swing.JButton();
+ btnAnterior = new javax.swing.JButton();
+ btnSiguiente = new javax.swing.JButton();
+ btnUltimo = new javax.swing.JButton();
+ lblId = new javax.swing.JLabel();
+ lblIdCliente = new javax.swing.JLabel();
+ lblNombre = new javax.swing.JLabel();
+ lblNombreCliente = new javax.swing.JLabel();
+ lblDireccion = new javax.swing.JLabel();
+ lblDireccionCliente = new javax.swing.JLabel();
+ btnNuevo = new javax.swing.JButton();
+ btnEditar = new javax.swing.JButton();
+ btnEliminar = new javax.swing.JButton();
+
+ jfNuevoCliente.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
+ jfNuevoCliente.setResizable(false);
+ jfNuevoCliente.setSize(new java.awt.Dimension(262, 185));
+
+ lblVNCTitulo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
+ lblVNCTitulo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
+ lblVNCTitulo.setText("Nuevo Cliente");
+
+ lblVNCNombre.setFont(new java.awt.Font("Noto Sans", 1, 12)); // NOI18N
+ lblVNCNombre.setText("Nombre:");
+
+ lblVNCDireccion.setFont(new java.awt.Font("Noto Sans", 1, 12)); // NOI18N
+ lblVNCDireccion.setText("Direccion:");
+
+ btnVNCAceptar.setText("Aceptar");
+ btnVNCAceptar.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ btnVNCAceptarActionPerformed(evt);
+ }
+ });
+
+ btnVNCCancelar.setText("Cancelar");
+ btnVNCCancelar.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ btnVNCCancelarActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout jpVNCLayout = new javax.swing.GroupLayout(jpVNC);
+ jpVNC.setLayout(jpVNCLayout);
+ jpVNCLayout.setHorizontalGroup(
+ jpVNCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jpVNCLayout.createSequentialGroup()
+ .addGroup(jpVNCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(lblVNCNombre)
+ .addComponent(lblVNCDireccion))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(jpVNCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(txtVNCNombre)
+ .addComponent(txtVNCDireccion)))
+ .addGroup(jpVNCLayout.createSequentialGroup()
+ .addGap(41, 41, 41)
+ .addComponent(btnVNCAceptar)
+ .addGap(18, 18, 18)
+ .addComponent(btnVNCCancelar)
+ .addContainerGap(61, Short.MAX_VALUE))
+ );
+ jpVNCLayout.setVerticalGroup(
+ jpVNCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jpVNCLayout.createSequentialGroup()
+ .addGroup(jpVNCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(lblVNCNombre)
+ .addComponent(txtVNCNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(jpVNCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(lblVNCDireccion)
+ .addComponent(txtVNCDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addGap(18, 18, 18)
+ .addGroup(jpVNCLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(btnVNCAceptar)
+ .addComponent(btnVNCCancelar))
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ javax.swing.GroupLayout jfNuevoClienteLayout = new javax.swing.GroupLayout(jfNuevoCliente.getContentPane());
+ jfNuevoCliente.getContentPane().setLayout(jfNuevoClienteLayout);
+ jfNuevoClienteLayout.setHorizontalGroup(
+ jfNuevoClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jfNuevoClienteLayout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(jfNuevoClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jpVNC, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(lblVNCTitulo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ .addContainerGap())
+ );
+ jfNuevoClienteLayout.setVerticalGroup(
+ jfNuevoClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jfNuevoClienteLayout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(lblVNCTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(jpVNC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addContainerGap())
+ );
+
+ jfEditarCliente.setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
+ jfEditarCliente.setResizable(false);
+ jfEditarCliente.setSize(new java.awt.Dimension(262, 214));
+
+ lblVECTitulo.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
+ lblVECTitulo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
+ lblVECTitulo.setText("Editar Cliente");
+
+ lblVECId.setFont(new java.awt.Font("Noto Sans", 1, 12)); // NOI18N
+ lblVECId.setText("ID:");
+
+ lblVECIdCliente.setText(" ");
+
+ lblVECNombre.setFont(new java.awt.Font("Noto Sans", 1, 12)); // NOI18N
+ lblVECNombre.setText("Nombre:");
+
+ lblVECDireccion.setFont(new java.awt.Font("Noto Sans", 1, 12)); // NOI18N
+ lblVECDireccion.setText("Direccion:");
+
+ btnVECAceptar.setText("Aceptar");
+ btnVECAceptar.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ btnVECAceptarActionPerformed(evt);
+ }
+ });
+
+ btnVECCancelar.setText("Cancelar");
+ btnVECCancelar.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ btnVECCancelarActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout jpVECLayout = new javax.swing.GroupLayout(jpVEC);
+ jpVEC.setLayout(jpVECLayout);
+ jpVECLayout.setHorizontalGroup(
+ jpVECLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jpVECLayout.createSequentialGroup()
+ .addGap(41, 41, 41)
+ .addComponent(btnVECAceptar)
+ .addGap(18, 18, 18)
+ .addComponent(btnVECCancelar)
+ .addContainerGap(61, Short.MAX_VALUE))
+ .addGroup(jpVECLayout.createSequentialGroup()
+ .addGroup(jpVECLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(lblVECDireccion)
+ .addComponent(lblVECNombre)
+ .addComponent(lblVECId))
+ .addGap(6, 6, 6)
+ .addGroup(jpVECLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jpVECLayout.createSequentialGroup()
+ .addComponent(lblVECIdCliente)
+ .addGap(0, 0, Short.MAX_VALUE))
+ .addComponent(txtVECNombre)
+ .addComponent(txtVECDireccion)))
+ );
+ jpVECLayout.setVerticalGroup(
+ jpVECLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jpVECLayout.createSequentialGroup()
+ .addGroup(jpVECLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(lblVECId)
+ .addComponent(lblVECIdCliente))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(jpVECLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(lblVECNombre)
+ .addComponent(txtVECNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(jpVECLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(lblVECDireccion)
+ .addComponent(txtVECDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(jpVECLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(btnVECAceptar)
+ .addComponent(btnVECCancelar))
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ javax.swing.GroupLayout jfEditarClienteLayout = new javax.swing.GroupLayout(jfEditarCliente.getContentPane());
+ jfEditarCliente.getContentPane().setLayout(jfEditarClienteLayout);
+ jfEditarClienteLayout.setHorizontalGroup(
+ jfEditarClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jfEditarClienteLayout.createSequentialGroup()
+ .addContainerGap()
+ .addGroup(jfEditarClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(jpVEC, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addComponent(lblVECTitulo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ .addContainerGap())
+ );
+ jfEditarClienteLayout.setVerticalGroup(
+ jfEditarClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jfEditarClienteLayout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(lblVECTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(jpVEC, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+
+ setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
+ setResizable(false);
+ addWindowListener(new java.awt.event.WindowAdapter() {
+ public void windowClosed(java.awt.event.WindowEvent evt) {
+ formWindowClosed(evt);
+ }
+ });
+
+ lblTitulo.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
+ lblTitulo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
+ lblTitulo.setText("Gestor de clientes");
+
+ btnPrimero.setText("|<");
+ btnPrimero.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ btnPrimeroActionPerformed(evt);
+ }
+ });
+
+ btnAnterior.setText("<<");
+ btnAnterior.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ btnAnteriorActionPerformed(evt);
+ }
+ });
+
+ btnSiguiente.setText(">>");
+ btnSiguiente.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ btnSiguienteActionPerformed(evt);
+ }
+ });
+
+ btnUltimo.setText(">|");
+ btnUltimo.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ btnUltimoActionPerformed(evt);
+ }
+ });
+
+ lblId.setFont(new java.awt.Font("Noto Sans", 1, 12)); // NOI18N
+ lblId.setText("ID:");
+
+ lblIdCliente.setText(" ");
+
+ lblNombre.setFont(new java.awt.Font("Noto Sans", 1, 12)); // NOI18N
+ lblNombre.setText("Nombre:");
+
+ lblNombreCliente.setText(" ");
+
+ lblDireccion.setFont(new java.awt.Font("Noto Sans", 1, 12)); // NOI18N
+ lblDireccion.setText("Dirección:");
+
+ lblDireccionCliente.setText(" ");
+
+ btnNuevo.setText("NUEVO");
+ btnNuevo.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ btnNuevoActionPerformed(evt);
+ }
+ });
+
+ btnEditar.setText("EDITAR");
+ btnEditar.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ btnEditarActionPerformed(evt);
+ }
+ });
+
+ btnEliminar.setText("ELIMINAR");
+ btnEliminar.addActionListener(new java.awt.event.ActionListener() {
+ public void actionPerformed(java.awt.event.ActionEvent evt) {
+ btnEliminarActionPerformed(evt);
+ }
+ });
+
+ javax.swing.GroupLayout jPanelVPLayout = new javax.swing.GroupLayout(jPanelVP);
+ jPanelVP.setLayout(jPanelVPLayout);
+ jPanelVPLayout.setHorizontalGroup(
+ jPanelVPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(lblTitulo, javax.swing.GroupLayout.DEFAULT_SIZE, 519, Short.MAX_VALUE)
+ .addGroup(jPanelVPLayout.createSequentialGroup()
+ .addGap(24, 24, 24)
+ .addGroup(jPanelVPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanelVPLayout.createSequentialGroup()
+ .addGroup(jPanelVPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanelVPLayout.createSequentialGroup()
+ .addComponent(lblNombre)
+ .addGap(18, 18, 18)
+ .addGroup(jPanelVPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addComponent(lblIdCliente)
+ .addComponent(lblNombreCliente)))
+ .addGroup(jPanelVPLayout.createSequentialGroup()
+ .addComponent(lblDireccion)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addComponent(lblDireccionCliente)))
+ .addGap(0, 0, Short.MAX_VALUE))
+ .addGroup(jPanelVPLayout.createSequentialGroup()
+ .addComponent(lblId)
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
+ .addGroup(jPanelVPLayout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(btnPrimero, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(btnAnterior, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(btnSiguiente, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(btnUltimo, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addGap(50, 50, 50)
+ .addComponent(btnNuevo)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(btnEditar)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addComponent(btnEliminar)
+ .addGap(0, 0, Short.MAX_VALUE))
+ );
+ jPanelVPLayout.setVerticalGroup(
+ jPanelVPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(jPanelVPLayout.createSequentialGroup()
+ .addComponent(lblTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
+ .addGroup(jPanelVPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(btnPrimero)
+ .addComponent(btnAnterior)
+ .addComponent(btnSiguiente)
+ .addComponent(btnUltimo)
+ .addComponent(btnNuevo)
+ .addComponent(btnEditar)
+ .addComponent(btnEliminar))
+ .addGap(24, 24, 24)
+ .addGroup(jPanelVPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(lblId)
+ .addComponent(lblIdCliente))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(jPanelVPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(lblNombre)
+ .addComponent(lblNombreCliente))
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
+ .addGroup(jPanelVPLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
+ .addComponent(lblDireccion)
+ .addComponent(lblDireccionCliente))
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
+ getContentPane().setLayout(layout);
+ layout.setHorizontalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jPanelVP, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addContainerGap())
+ );
+ layout.setVerticalGroup(
+ layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
+ .addGroup(layout.createSequentialGroup()
+ .addContainerGap()
+ .addComponent(jPanelVP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
+ );
+
+ pack();
+ }// //GEN-END:initComponents
+
+ private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
+
+ // Cerramos el ResultSet de clientes
+ try {
+ rsClientes.close();
+ } catch (SQLException ex) {
+ ex.printStackTrace();
+ }
+
+ // Cerramos la conexión a la base de datos
+ DBManager.close();
+ }//GEN-LAST:event_formWindowClosed
+
+ private void btnPrimeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPrimeroActionPerformed
+ muestraClientePrimero();
+ }//GEN-LAST:event_btnPrimeroActionPerformed
+
+ private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAnteriorActionPerformed
+ muestraClienteAnterior();
+ }//GEN-LAST:event_btnAnteriorActionPerformed
+
+ private void btnSiguienteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSiguienteActionPerformed
+ muestraClienteSiguiente();
+ }//GEN-LAST:event_btnSiguienteActionPerformed
+
+ private void btnUltimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUltimoActionPerformed
+ muestraClienteUltimo();
+ }//GEN-LAST:event_btnUltimoActionPerformed
+
+ // Pide los clientes a la base de datos y los guarda en ResultSet rsClientes
+ private void obtenerClientes() {
+ try {
+ // Cerramos el ResultSet actual
+ if (rsClientes != null) {
+ rsClientes.close();
+ }
+
+ // Pedimos la tabla clientes a la base de datos
+ rsClientes = DBManager.getTablaClientes(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
+
+ // Movemos cursor al primero
+ clienteValido = rsClientes.first();
+
+ } catch (SQLException ex) {
+ ex.printStackTrace();
+ }
+ }
+
+ private void muestraClientePrimero() {
+ try {
+ clienteValido = rsClientes.first();
+ muestraDatosCliente();
+ } catch (SQLException ex) {
+ muestraVentanaErrorSQL(ex);
+ } catch (Exception ex) {
+ muestraVentanaError(ex);
+ }
+ }
+
+ private void muestraClienteAnterior() {
+ try {
+ if (!rsClientes.isFirst()) {
+ clienteValido = rsClientes.previous();
+ muestraDatosCliente();
+ }
+ } catch (SQLException ex) {
+ muestraVentanaErrorSQL(ex);
+ } catch (Exception ex) {
+ muestraVentanaError(ex);
+ }
+ }
+
+ private void muestraClienteSiguiente() {
+ try {
+ if (!rsClientes.isLast()) {
+ clienteValido = rsClientes.next();
+ muestraDatosCliente();
+ }
+ } catch (SQLException ex) {
+ muestraVentanaErrorSQL(ex);
+ } catch (Exception ex) {
+ muestraVentanaError(ex);
+ }
+ }
+
+ private void muestraClienteUltimo() {
+ try {
+ clienteValido = rsClientes.last();
+ muestraDatosCliente();
+ } catch (SQLException ex) {
+ muestraVentanaErrorSQL(ex);
+ } catch (Exception ex) {
+ muestraVentanaError(ex);
+ }
+ }
+
+ // Muestra en los componentes los datos del cliente al que apunta el cursor de rsclientes
+ private void muestraDatosCliente() {
+
+ int id = 0;
+ String nombre = "";
+ String direccion = "";
+
+ // Obtenemos los datos del cliente actual (si es válido)
+ if (clienteValido) {
+ try {
+ id = rsClientes.getInt("id");
+ nombre = rsClientes.getString("nombre");
+ direccion = rsClientes.getString("direccion");
+
+ } catch (SQLException ex) {
+ muestraVentanaError(ex);
+ }
+ }
+
+ // Mostramos datos en la ventana
+ lblIdCliente.setText("" + id);
+ lblNombreCliente.setText(nombre);
+ lblDireccionCliente.setText(direccion);
+ }
+
+ private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed
+
+ if (!clienteValido) {
+ muestraVentanaAviso("No se puede editar el cliente.\n¿Es posible que no haya clientes?");
+ } else {
+
+ try {
+ // Obtenemos los datos del cliente actual
+ int id = rsClientes.getInt("id");
+ lblVECIdCliente.setText("" + id);
+ String nombre = rsClientes.getString("nombre");
+ txtVECNombre.setText(nombre);
+ String direccion = rsClientes.getString("direccion");
+ txtVECDireccion.setText(direccion);
+
+ // Ocultamos ventana principal
+ this.setVisible(false);
+
+ // Mostramos ventana de editar cliente
+ jfEditarCliente.setVisible(true);
+
+ } catch (SQLException ex) {
+ muestraVentanaError(ex);
+ }
+ }
+ }//GEN-LAST:event_btnEditarActionPerformed
+
+ private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
+
+ if (!clienteValido) {
+ muestraVentanaAviso("No se puede eliminar el cliente.\n¿Es posible que no haya clientes?");
+ } else {
+ // Ventana para que el usuario confirme
+ boolean aceptado = muestraVentanaAceptarCancelar("¿Está seguro de que desea eliminar el cliente?");
+
+ // Si respondió que sí, eliminamos el cliente y actualizamos datos
+ if (aceptado) {
+ try {
+ // Eliminamos el cliente actual
+ int id = Integer.parseInt(lblIdCliente.getText());
+ DBManager.deleteCliente(id);
+
+ // Actualizamos datos de clientes
+ obtenerClientes();
+ muestraDatosCliente();
+ } catch (Exception ex) {
+ muestraVentanaError(ex);
+ }
+ }
+ }
+
+ }//GEN-LAST:event_btnEliminarActionPerformed
+
+ private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed
+ // Ocultamos ventana principal
+ this.setVisible(false);
+
+ // Mostramos ventana de nuevo cliente con campos vacíos
+ txtVNCNombre.setText("");
+ txtVNCDireccion.setText("");
+ jfNuevoCliente.setVisible(true);
+ }//GEN-LAST:event_btnNuevoActionPerformed
+
+ private void btnVNCAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVNCAceptarActionPerformed
+ // Registramos nuevo cliente en la base de datos
+ String nombre = txtVNCNombre.getText();
+ String direccion = txtVNCDireccion.getText();
+ DBManager.insertCliente(nombre, direccion);
+
+ // Ocultamos ventana de nuevo cliente y mostramos ventana principal
+ jfNuevoCliente.setVisible(false);
+ this.setVisible(true);
+
+ // Actualizamos datos y mostramos el último
+ obtenerClientes();
+ muestraClienteUltimo();
+ }//GEN-LAST:event_btnVNCAceptarActionPerformed
+
+ private void btnVNCCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVNCCancelarActionPerformed
+ jfNuevoCliente.setVisible(false);
+ this.setVisible(true);
+ }//GEN-LAST:event_btnVNCCancelarActionPerformed
+
+ private void btnVECAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVECAceptarActionPerformed
+ // Registramos nuevo cliente en la base de datos
+ int id = Integer.parseInt(lblVECIdCliente.getText());
+ String nombre = txtVECNombre.getText();
+ String direccion = txtVECDireccion.getText();
+ DBManager.updateCliente(id, nombre, direccion);
+
+ // Ocultamos ventana de nuevo cliente y mostramos ventana principal
+ jfEditarCliente.setVisible(false);
+ this.setVisible(true);
+
+ // Actualizamos datos y mostramos el último
+ obtenerClientes();
+ muestraClientePrimero();
+ }//GEN-LAST:event_btnVECAceptarActionPerformed
+
+ private void btnVECCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVECCancelarActionPerformed
+ jfEditarCliente.setVisible(false);
+ this.setVisible(true);
+ }//GEN-LAST:event_btnVECCancelarActionPerformed
+
+ // Muestra una ventana de error tipo SQLException
+ private void muestraVentanaErrorSQL(SQLException ex) {
+ ex.printStackTrace();
+ JOptionPane.showMessageDialog(this, "Error SQL:\n" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
+ }
+
+ // Muestra una ventana de error tipo Exception
+ private void muestraVentanaError(Exception ex) {
+ ex.printStackTrace();
+ JOptionPane.showMessageDialog(this, "Error inesperado:\n" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
+ }
+
+ // Muestra una ventana de aviso con el mensaje indicado
+ private void muestraVentanaAviso(String mensaje) {
+ JOptionPane.showMessageDialog(this, mensaje, "Aviso", JOptionPane.WARNING_MESSAGE);
+ }
+
+ // Muestra una ventana de aceptar/cancelar y devuelve true si le dió a aceptar
+ private boolean muestraVentanaAceptarCancelar(String mensaje) {
+ int result = JOptionPane.showConfirmDialog(this, mensaje, "Confirme la acción", JOptionPane.OK_CANCEL_OPTION);
+ return (result == 0);
+ }
+
+ public static void main(String args[]) {
+ /* Set the Nimbus look and feel */
+ //
+ /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
+ * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
+ */
+ try {
+ for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
+ if ("Nimbus".equals(info.getName())) {
+ javax.swing.UIManager.setLookAndFeel(info.getClassName());
+ break;
+ }
+ }
+ } catch (ClassNotFoundException ex) {
+ java.util.logging.Logger.getLogger(GestionClientesIGU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
+ } catch (InstantiationException ex) {
+ java.util.logging.Logger.getLogger(GestionClientesIGU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
+ } catch (IllegalAccessException ex) {
+ java.util.logging.Logger.getLogger(GestionClientesIGU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
+ } catch (javax.swing.UnsupportedLookAndFeelException ex) {
+ java.util.logging.Logger.getLogger(GestionClientesIGU.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
+ }
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+
+ /* Create and display the form */
+ java.awt.EventQueue.invokeLater(new Runnable() {
+ public void run() {
+ new GestionClientesIGU().setVisible(true);
+ }
+ });
+ }
+
+ // Variables declaration - do not modify//GEN-BEGIN:variables
+ private javax.swing.JButton btnAnterior;
+ private javax.swing.JButton btnEditar;
+ private javax.swing.JButton btnEliminar;
+ private javax.swing.JButton btnNuevo;
+ private javax.swing.JButton btnPrimero;
+ private javax.swing.JButton btnSiguiente;
+ private javax.swing.JButton btnUltimo;
+ private javax.swing.JButton btnVECAceptar;
+ private javax.swing.JButton btnVECCancelar;
+ private javax.swing.JButton btnVNCAceptar;
+ private javax.swing.JButton btnVNCCancelar;
+ private javax.swing.JPanel jPanelVP;
+ private javax.swing.JFrame jfEditarCliente;
+ private javax.swing.JFrame jfNuevoCliente;
+ private javax.swing.JPanel jpVEC;
+ private javax.swing.JPanel jpVNC;
+ private javax.swing.JLabel lblDireccion;
+ private javax.swing.JLabel lblDireccionCliente;
+ private javax.swing.JLabel lblId;
+ private javax.swing.JLabel lblIdCliente;
+ private javax.swing.JLabel lblNombre;
+ private javax.swing.JLabel lblNombreCliente;
+ private javax.swing.JLabel lblTitulo;
+ private javax.swing.JLabel lblVECDireccion;
+ private javax.swing.JLabel lblVECId;
+ private javax.swing.JLabel lblVECIdCliente;
+ private javax.swing.JLabel lblVECNombre;
+ private javax.swing.JLabel lblVECTitulo;
+ private javax.swing.JLabel lblVNCDireccion;
+ private javax.swing.JLabel lblVNCNombre;
+ private javax.swing.JLabel lblVNCTitulo;
+ private javax.swing.JTextField txtVECDireccion;
+ private javax.swing.JTextField txtVECNombre;
+ private javax.swing.JTextField txtVNCDireccion;
+ private javax.swing.JTextField txtVNCNombre;
+ // End of variables declaration//GEN-END:variables
+}
diff --git a/src/main/java/iesthiar/gestorClientes/tienda.sql b/src/main/java/iesthiar/gestorClientes/tienda.sql
new file mode 100644
index 0000000..59880d2
--- /dev/null
+++ b/src/main/java/iesthiar/gestorClientes/tienda.sql
@@ -0,0 +1,74 @@
+-- phpMyAdmin SQL Dump
+-- version 5.0.2
+-- https://www.phpmyadmin.net/
+--
+-- Servidor: localhost
+-- Tiempo de generación: 30-04-2020 a las 10:39:43
+-- Versión del servidor: 10.4.11-MariaDB
+-- Versión de PHP: 7.4.4
+
+SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
+START TRANSACTION;
+SET time_zone = "+00:00";
+
+
+/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
+/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
+/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
+/*!40101 SET NAMES utf8mb4 */;
+
+--
+-- Base de datos: `tienda`
+--
+
+-- --------------------------------------------------------
+
+--
+-- Estructura de tabla para la tabla `clientes`
+--
+
+CREATE TABLE `clientes` (
+ `id` int(11) NOT NULL,
+ `nombre` varchar(50) NOT NULL,
+ `direccion` varchar(100) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=latin1;
+
+--
+-- Volcado de datos para la tabla `clientes`
+--
+
+INSERT INTO `clientes` (`id`, `nombre`, `direccion`) VALUES
+(1, 'Lionel', 'Valencia'),
+(2, 'Sergi', 'Valencia'),
+(3, 'Alfredo', 'Valencia'),
+(4, 'Paco', 'Valencia'),
+(5, 'Maria', 'Castellón'),
+(6, 'Pepito', 'Alicante'),
+(7, 'Luis', 'Elx'),
+(8, 'Antonia', 'Xàtiva'),
+(9, 'Carmen', 'Paterna');
+
+--
+-- Índices para tablas volcadas
+--
+
+--
+-- Indices de la tabla `clientes`
+--
+ALTER TABLE `clientes`
+ ADD PRIMARY KEY (`id`);
+
+--
+-- AUTO_INCREMENT de las tablas volcadas
+--
+
+--
+-- AUTO_INCREMENT de la tabla `clientes`
+--
+ALTER TABLE `clientes`
+ MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
+COMMIT;
+
+/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
+/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
+/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
diff --git a/src/main/java/iesthiar/gestorClientesDAO/App.java b/src/main/java/iesthiar/gestorClientesDAO/App.java
new file mode 100644
index 0000000..0475c08
--- /dev/null
+++ b/src/main/java/iesthiar/gestorClientesDAO/App.java
@@ -0,0 +1,35 @@
+package iesthiar.gestorClientesDAO;
+
+import java.io.IOException;
+
+import javafx.application.Application;
+import javafx.fxml.FXMLLoader;
+import javafx.scene.Parent;
+import javafx.scene.Scene;
+import javafx.stage.Stage;
+
+public class App extends Application {
+
+ private static Scene scene;
+
+ @Override
+ public void start(Stage stage) throws IOException {
+ scene = new Scene(loadFXML("gestorClientes"), 640, 480);
+ stage.setScene(scene);
+ stage.show();
+ }
+
+ static void setRoot(String fxml) throws IOException {
+ scene.setRoot(loadFXML(fxml));
+ }
+
+ private static Parent loadFXML(String fxml) throws IOException {
+ FXMLLoader fxmlLoader = new FXMLLoader(App.class.getResource(fxml + ".fxml"));
+ return fxmlLoader.load();
+ }
+
+ public static void main(String[] args) {
+ launch();
+ }
+
+}
\ No newline at end of file
diff --git a/src/main/java/iesthiar/gestorClientesDAO/Cliente.java b/src/main/java/iesthiar/gestorClientesDAO/Cliente.java
new file mode 100644
index 0000000..35cec59
--- /dev/null
+++ b/src/main/java/iesthiar/gestorClientesDAO/Cliente.java
@@ -0,0 +1,50 @@
+package iesthiar.gestorClientesDAO;
+
+import java.io.Serializable;
+
+public class Cliente implements Serializable {
+ private static final long serialVersionUID=1L;
+ long id;
+ String nombre;
+ String direccion;
+
+ public Cliente(long id, String nombre, String direccion) {
+ this.id = id;
+ this.nombre = nombre;
+ this.direccion = direccion;
+ }
+ // Junto con getters/setters
+ public Cliente(String nombre,String direccion){
+ this(0,nombre,direccion);
+ }
+
+
+ public long getId() {
+ return id;
+ }
+
+ public void setId(long id) {
+ this.id = id;
+ }
+
+ public String getNombre() {
+ return nombre;
+ }
+
+ public void setNombre(String nombre) {
+ this.nombre = nombre;
+ }
+
+ public String getDireccion() {
+ return direccion;
+ }
+
+ public void setDireccion(String direccion) {
+ this.direccion = direccion;
+ }
+
+ @Override
+ public String toString() {
+ return nombre;
+ }
+}
diff --git a/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoMysql.java b/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoMysql.java
new file mode 100644
index 0000000..e1baa2c
--- /dev/null
+++ b/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoMysql.java
@@ -0,0 +1,176 @@
+package iesthiar.gestorClientesDAO;
+
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.Properties;
+
+import javax.sql.DataSource;
+
+import org.apache.commons.dbcp2.BasicDataSource;
+
+public class ClienteDaoMysql implements Dao {
+
+ // Un DataSource es un intermediario para obtener las conexiones con la base de
+ // datos
+ private DataSource dataSource;
+ private static ClienteDaoMysql clienteDaoMysql=null;
+
+
+ // El constructor es privado para que no se puedan crear objetos de esta clase.
+ // Así se implementa el patrón singleton
+ private ClienteDaoMysql() {
+ // Configurar el BasicDataSource con los datos de la base de datos
+ String servidor, baseDatos, usuario, clave;
+ Properties datos = new Properties();
+ try (InputStream inputStream = new FileInputStream("db_config.properties")) {
+ datos.load(inputStream);
+ servidor = datos.getProperty("db.servidor");
+ baseDatos = datos.getProperty("db.baseDatos");
+ usuario = datos.getProperty("db.usuario");
+ clave = datos.getProperty("db.clave");
+
+ } catch (IOException | NullPointerException e) {
+ // Establecemos unos valores por defecto
+ servidor = "172.18.185.243";
+ baseDatos = "tienda";
+ usuario = "root";
+ clave = "example";
+ // Crear fichero de properties
+ crearFicheroProperties();
+ System.out.println("El fichero de configuración no existe");
+ }
+ // Creamos la fuente de datos
+ BasicDataSource basicDataSource = new BasicDataSource();
+ basicDataSource.setUrl("jdbc:mysql://" + servidor + ":3306/" + baseDatos);
+ basicDataSource.setUsername(usuario);
+ basicDataSource.setPassword(clave);
+ this.dataSource = basicDataSource;
+ }
+
+ // Implementación del patrón Singleton. Usamos un método para obtener objetos de la clase.
+ // Si no existe el objeto, lo creamos, y siempre devolvemos el mismo objeto. Sólo tenemos una instancia de este objeto
+ public static ClienteDaoMysql getClienteDaoMysql(){
+ if (clienteDaoMysql==null)
+ clienteDaoMysql=new ClienteDaoMysql();
+ return clienteDaoMysql;
+ }
+
+ private void crearFicheroProperties() {
+ Properties datos = new Properties();
+ datos.setProperty("db.servidor", "localhost");
+ datos.setProperty("db.puerto", "3306");
+ datos.setProperty("db.baseDatos", "geografia");
+ datos.setProperty("db.usuario", "root");
+ datos.setProperty("db.clave", "");
+ try {
+ datos.store(new FileOutputStream("db_config.properties"), "Configuración inicial BD");
+ } catch (IOException e) {
+ System.out.println("ERROR al escribir el fichero de properties");
+ }
+ }
+
+ @Override
+ public Optional obtener(long id) {
+ try (Connection conn = dataSource.getConnection();
+ PreparedStatement stmt = conn.prepareStatement("SELECT nombre, direccion FROM clientes WHERE id = ?")) {
+
+ stmt.setLong(1, id);
+
+ try (ResultSet rs = stmt.executeQuery()) {
+ if (rs.next()) {
+ String nombre = rs.getString("nombre");
+ String direccion = rs.getString("direccion");
+
+ Cliente cliente = new Cliente(id, nombre, direccion);
+ return Optional.of(cliente);
+ }
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+
+ return Optional.empty();
+ }
+
+ @Override
+ public List obtenerTodos() {
+ List clientes = new ArrayList<>();
+ try (Connection conn = dataSource.getConnection();
+ Statement stmt = conn.createStatement();
+ ResultSet rs = stmt.executeQuery("SELECT id, nombre, direccion FROM clientes")) {
+
+ while (rs.next()) {
+ long id = rs.getLong("id");
+ String nombre = rs.getString("nombre");
+ String direccion = rs.getString("direccion");
+
+ Cliente cliente = new Cliente(id, nombre, direccion);
+ clientes.add(cliente);
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ return clientes;
+ }
+
+ @Override
+ public void guardar(Cliente cliente) {
+ try (Connection conn = dataSource.getConnection();
+ PreparedStatement pst = conn.prepareStatement("insert into clientes(nombre,direccion) values (?,?)")) {
+
+ pst.setString(1, cliente.getNombre());
+ pst.setString(2, cliente.getDireccion());
+
+ pst.executeUpdate();
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void actualizar(Cliente cliente) {
+ try (Connection conn = dataSource.getConnection();
+ PreparedStatement pst = conn.prepareStatement("update clientes set nombre=?, direccion=? where id=?")) {
+
+ pst.setString(1, cliente.getNombre());
+ pst.setString(2, cliente.getDireccion());
+ pst.setLong(3, cliente.getId());
+
+ pst.executeUpdate();
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public void borrar(Cliente cliente) {
+ try (Connection conn = dataSource.getConnection();
+ PreparedStatement pst = conn.prepareStatement("delete from clientes where id=?")) {
+
+ pst.setLong(1, cliente.getId());
+
+ pst.executeUpdate();
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ @Override
+ public boolean activa() {
+ try (Connection conn = dataSource.getConnection()) {
+ return true;
+ } catch (SQLException e) {
+ return false;
+ }
+ }
+}
diff --git a/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoSerilizable.java b/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoSerilizable.java
new file mode 100644
index 0000000..56b9fc0
--- /dev/null
+++ b/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoSerilizable.java
@@ -0,0 +1,47 @@
+package iesthiar.gestorClientesDAO;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+public class ClienteDaoSerilizable implements Dao{
+
+ private Map clientes;
+
+ public ClienteDaoSerilizable(){
+ // Leer objetos del fichero serializado.
+ // Fichero se guarda en resources
+ // Donde dejo los objetos?
+ }
+
+ @Override
+ public Optional obtener(long id) {
+ return Optional.empty();
+ }
+
+ @Override
+ public List obtenerTodos() {
+ return null;
+ }
+
+ @Override
+ public void guardar(Cliente cliente) {
+
+ }
+
+ @Override
+ public void actualizar(Cliente cliente) {
+
+ }
+
+ @Override
+ public void borrar(Cliente cliente) {
+
+ }
+
+ @Override
+ public boolean activa() {
+ // TODO Auto-generated method stub
+ throw new UnsupportedOperationException("Unimplemented method 'activa'");
+ }
+}
diff --git a/src/main/java/iesthiar/gestorClientesDAO/Dao.java b/src/main/java/iesthiar/gestorClientesDAO/Dao.java
new file mode 100644
index 0000000..de65556
--- /dev/null
+++ b/src/main/java/iesthiar/gestorClientesDAO/Dao.java
@@ -0,0 +1,13 @@
+package iesthiar.gestorClientesDAO;
+
+import java.util.List;
+import java.util.Optional;
+
+public interface Dao {
+ Optional obtener(long id);
+ List obtenerTodos();
+ void guardar(T t);
+ void actualizar(T t);
+ void borrar(T t);
+ boolean activa();
+}
diff --git a/src/main/java/iesthiar/gestorClientesDAO/gestorClientesControlador.java b/src/main/java/iesthiar/gestorClientesDAO/gestorClientesControlador.java
new file mode 100644
index 0000000..2b266d4
--- /dev/null
+++ b/src/main/java/iesthiar/gestorClientesDAO/gestorClientesControlador.java
@@ -0,0 +1,122 @@
+package iesthiar.gestorClientesDAO;
+
+import java.net.URL;
+import java.util.Optional;
+import java.util.ResourceBundle;
+
+import javafx.event.ActionEvent;
+import javafx.fxml.FXML;
+import javafx.fxml.Initializable;
+import javafx.scene.control.Alert;
+import javafx.scene.control.Alert.AlertType;
+import javafx.scene.control.Button;
+import javafx.scene.control.ButtonType;
+import javafx.scene.control.ComboBox;
+import javafx.scene.control.Label;
+import javafx.scene.control.TextField;
+
+public class gestorClientesControlador implements Initializable {
+ @FXML
+ private ComboBox clientesCBox;
+
+ @FXML
+ private TextField idTF;
+ @FXML
+ private TextField nombreTF;
+ @FXML
+ private TextField direccionTF;
+ @FXML
+ private Label mensajes;
+ @FXML
+ private Button modificarButton;
+ @FXML
+ private Button borrarButton;
+
+ private Dao dao;
+ private Cliente clienteSeleccionado;
+
+ @Override
+ public void initialize(URL location, ResourceBundle resources) {
+ dao = ClienteDaoMysql.getClienteDaoMysql();
+ if (!dao.activa()) {
+ Alert alerta = new Alert(AlertType.ERROR);
+ alerta.setHeaderText("ERROR GRAVE");
+ alerta.setContentText("Se ha producido un error al abrir la base de datos");
+ alerta.showAndWait();
+ System.exit(1);
+ }
+
+ clientesCBox.getItems().setAll(dao.obtenerTodos());
+ }
+
+ @FXML
+ public void accionCB(ActionEvent ae) {
+ clienteSeleccionado = (Cliente) ((ComboBox) ae.getSource()).getValue();
+ idTF.setText("" + clienteSeleccionado.id);
+ nombreTF.setText(clienteSeleccionado.nombre);
+ direccionTF.setText(clienteSeleccionado.direccion);
+ mensajes.setText("");
+ }
+
+ @FXML
+ public void nuevoCliente(ActionEvent ae) {
+ Button fuente=(Button)ae.getSource();
+ if (fuente.getText().equals("Nuevo")){
+ // Preparamos para crear un nuevo cliente
+ fuente.setText("Crear");
+ modificarButton.setDisable(true);
+ borrarButton.setDisable(true);
+ clientesCBox.setDisable(true);
+ idTF.setText("");
+ direccionTF.setText("");
+ nombreTF.setText("");
+ idTF.setEditable(true);
+ idTF.requestFocus();
+ } else {
+ // Dar de alta realmente
+ if (idTF.getText().matches("^[0-9]+$") && !nombreTF.getText().equals("") && !direccionTF.getText().equals("")){
+ Cliente nuevoCliente=new Cliente(Long.parseLong(idTF.getText()),nombreTF.getText(), direccionTF.getText());
+ dao.guardar(nuevoCliente);
+ mensajes.setText("Cliente creado correctamente");
+ modificarButton.setDisable(false);
+ borrarButton.setDisable(false);
+ clientesCBox.setDisable(false);
+ fuente.setText("Nuevo");
+ direccionTF.setText("");
+ nombreTF.setText("");
+ idTF.setEditable(false);
+ clientesCBox.getItems().add(nuevoCliente);
+ }
+ }
+ }
+
+ @FXML
+ public void modificar() {
+ if (clienteSeleccionado != null) {
+ clienteSeleccionado.setDireccion(direccionTF.getText());
+ clienteSeleccionado.setNombre(nombreTF.getText());
+ dao.actualizar(clienteSeleccionado);
+ mensajes.setText("Cliente modificado correctamente");
+ }
+ }
+
+ @FXML
+ public void borrarCliente() {
+ if (clienteSeleccionado != null && confirmacion("¿Borrar el cliente seleccionado?")) {
+ dao.borrar(clienteSeleccionado);
+ clientesCBox.getItems().remove(clienteSeleccionado);
+ mensajes.setText("Cliente borrado correctamente");
+ }
+ }
+
+ private boolean confirmacion(String mensaje) {
+ Alert alerta = new Alert(AlertType.CONFIRMATION);
+ alerta.setHeaderText("Se necesita confirmación");
+ alerta.setContentText(mensaje);
+ Optional res = alerta.showAndWait();
+ if (res.get() == ButtonType.OK)
+ return true;
+ else
+ return false;
+ }
+}
diff --git a/src/main/java/module-info.java b/src/main/java/module-info.java
index e58bae0..88aca3b 100644
--- a/src/main/java/module-info.java
+++ b/src/main/java/module-info.java
@@ -1,7 +1,15 @@
module iesthiar {
requires javafx.controls;
requires javafx.fxml;
+ requires java.sql;
+ requires java.desktop;
+ requires javafx.graphics;
+ requires org.apache.commons.dbcp2;
opens iesthiar to javafx.fxml;
exports iesthiar;
+
+ opens iesthiar.gestorClientesDAO to javafx.fxml;
+ exports iesthiar.gestorClientesDAO;
+
}
diff --git a/src/main/resources/iesthiar/gestorClientesDAO/gestorClientes.fxml b/src/main/resources/iesthiar/gestorClientesDAO/gestorClientes.fxml
new file mode 100644
index 0000000..e1948bc
--- /dev/null
+++ b/src/main/resources/iesthiar/gestorClientesDAO/gestorClientes.fxml
@@ -0,0 +1,67 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/iesthiar/gestorClientesDAO/tienda.sql b/src/main/resources/iesthiar/gestorClientesDAO/tienda.sql
new file mode 100644
index 0000000..59880d2
--- /dev/null
+++ b/src/main/resources/iesthiar/gestorClientesDAO/tienda.sql
@@ -0,0 +1,74 @@
+-- phpMyAdmin SQL Dump
+-- version 5.0.2
+-- https://www.phpmyadmin.net/
+--
+-- Servidor: localhost
+-- Tiempo de generación: 30-04-2020 a las 10:39:43
+-- Versión del servidor: 10.4.11-MariaDB
+-- Versión de PHP: 7.4.4
+
+SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
+START TRANSACTION;
+SET time_zone = "+00:00";
+
+
+/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
+/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
+/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
+/*!40101 SET NAMES utf8mb4 */;
+
+--
+-- Base de datos: `tienda`
+--
+
+-- --------------------------------------------------------
+
+--
+-- Estructura de tabla para la tabla `clientes`
+--
+
+CREATE TABLE `clientes` (
+ `id` int(11) NOT NULL,
+ `nombre` varchar(50) NOT NULL,
+ `direccion` varchar(100) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=latin1;
+
+--
+-- Volcado de datos para la tabla `clientes`
+--
+
+INSERT INTO `clientes` (`id`, `nombre`, `direccion`) VALUES
+(1, 'Lionel', 'Valencia'),
+(2, 'Sergi', 'Valencia'),
+(3, 'Alfredo', 'Valencia'),
+(4, 'Paco', 'Valencia'),
+(5, 'Maria', 'Castellón'),
+(6, 'Pepito', 'Alicante'),
+(7, 'Luis', 'Elx'),
+(8, 'Antonia', 'Xàtiva'),
+(9, 'Carmen', 'Paterna');
+
+--
+-- Índices para tablas volcadas
+--
+
+--
+-- Indices de la tabla `clientes`
+--
+ALTER TABLE `clientes`
+ ADD PRIMARY KEY (`id`);
+
+--
+-- AUTO_INCREMENT de las tablas volcadas
+--
+
+--
+-- AUTO_INCREMENT de la tabla `clientes`
+--
+ALTER TABLE `clientes`
+ MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
+COMMIT;
+
+/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
+/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
+/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
diff --git a/src/main/resources/iesthiar/preparadas.fxml b/src/main/resources/iesthiar/preparadas.fxml
new file mode 100644
index 0000000..cdbfb08
--- /dev/null
+++ b/src/main/resources/iesthiar/preparadas.fxml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/iesthiar/primary.fxml b/src/main/resources/iesthiar/primary.fxml
deleted file mode 100644
index 32c3793..0000000
--- a/src/main/resources/iesthiar/primary.fxml
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/src/main/resources/iesthiar/pruebaConexion.fxml b/src/main/resources/iesthiar/pruebaConexion.fxml
new file mode 100644
index 0000000..d6f2c61
--- /dev/null
+++ b/src/main/resources/iesthiar/pruebaConexion.fxml
@@ -0,0 +1,82 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/main/resources/iesthiar/secondary.fxml b/src/main/resources/iesthiar/secondary.fxml
deleted file mode 100644
index 27ae05c..0000000
--- a/src/main/resources/iesthiar/secondary.fxml
+++ /dev/null
@@ -1,16 +0,0 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-