From 2389f2302b54b5aaa3c9ccce891c2cf77c056093 Mon Sep 17 00:00:00 2001 From: Joan Date: Wed, 12 Apr 2023 17:33:11 +0200 Subject: [PATCH 01/10] Table classes in process --- .../src/main/java/models/Attribute.java | 36 +++++++++++++++++++ .../src/main/java/models/TablaCliente.java | 23 ++++++++++++ Ejercicio1/src/main/java/models/Table.java | 26 ++++++++++++++ 3 files changed, 85 insertions(+) create mode 100644 Ejercicio1/src/main/java/models/Attribute.java create mode 100644 Ejercicio1/src/main/java/models/TablaCliente.java create mode 100644 Ejercicio1/src/main/java/models/Table.java diff --git a/Ejercicio1/src/main/java/models/Attribute.java b/Ejercicio1/src/main/java/models/Attribute.java new file mode 100644 index 0000000..6994aa4 --- /dev/null +++ b/Ejercicio1/src/main/java/models/Attribute.java @@ -0,0 +1,36 @@ +package models; + + +// esta clase representa el atributo de una tabla de una BD +public class Attribute { + public String name; + public String type; + public String type_cardinality = ""; + public String[] others = {}; + + // example: JEFE CHARVAR(30) NOT NULL REFERENCES EMPLEADO + // name="ID", type="CHARVAR", type_cardinality="(30)", + // others=["NOT", "NULL", "REFERENCES", "EMPLEADO"] + + + Attribute(String name, String type) { + this.name = name; + this.type = type; + } + Attribute(String name, String type, String type_cardinality) { + this.name = name; + this.type = type; + this.type_cardinality = type_cardinality; + } + Attribute(String name, String type, String type_cardinality, String others) { + this.name = name; + this.type = type; + this.type_cardinality = type_cardinality; + this.others = others.split(others); + } + + @Override + public String toString() { + return name + " " + type + type_cardinality + " " + others; + } +} diff --git a/Ejercicio1/src/main/java/models/TablaCliente.java b/Ejercicio1/src/main/java/models/TablaCliente.java new file mode 100644 index 0000000..f61bfce --- /dev/null +++ b/Ejercicio1/src/main/java/models/TablaCliente.java @@ -0,0 +1,23 @@ +package models; + +// en futuros ejercicios esta clase podrá contener más de una tabla +public class TablaCliente { + public Table tabla; + + public TablaCliente() { + Attribute[] attributes = { + new Attribute("id", "INT", "(11)", "NOT NULL AUTO_INCREMENT PRIMARY KEY"), + new Attribute("Nombre", "VARCHAR", "(250)", "NOT NULL"), + new Attribute("Apellido", "VARCHAR", "(250)", "NOT NULL"), + new Attribute("Direccion", "VARCHAR", "(250)", "NOT NULL"), + new Attribute("DNI", "VARCHAR", "(250)", "DEFAULT NULL"), + new Attribute("fecha", "DATE", "", "DEFAULT NULL"), + }; + tabla = new Table("cliente", attributes); + tabla.createTable(); + } + + + + +} diff --git a/Ejercicio1/src/main/java/models/Table.java b/Ejercicio1/src/main/java/models/Table.java new file mode 100644 index 0000000..880e750 --- /dev/null +++ b/Ejercicio1/src/main/java/models/Table.java @@ -0,0 +1,26 @@ +package models; + + +/* + * Esta clase es una forma genérica de representar tablas SQL + * usable para otros ejercicios similares + */ +public class Table { + private String name; + private Attribute[] attributes; + //TODO: foregin keys + + Table(String name, Attribute[] attributes) { + this.attributes = attributes; + this.name = name; + } + + public Attribute[] getAttributes() { + return attributes; + } + + public void createTable() { + + } + +} From fbe450a2a132113e92f54d0638cd093d63fcbfc3 Mon Sep 17 00:00:00 2001 From: Joan Date: Wed, 12 Apr 2023 17:34:35 +0200 Subject: [PATCH 02/10] coses d'eclipse --- .project | 11 +++++++ Ejercicio1/.classpath | 17 ++++++++++ Ejercicio1/.project | 11 +++++++ .../.settings/org.eclipse.jdt.apt.core.prefs | 2 ++ .../.settings/org.eclipse.jdt.core.prefs | 1 + .../target/classes/META-INF/MANIFEST.MF | 5 --- .../META-INF/maven/22/ta22/pom.properties | 7 ---- .../classes/META-INF/maven/22/ta22/pom.xml | 32 ------------------- 8 files changed, 42 insertions(+), 44 deletions(-) create mode 100644 Ejercicio1/.settings/org.eclipse.jdt.apt.core.prefs delete mode 100644 Ejercicio1/target/classes/META-INF/MANIFEST.MF delete mode 100644 Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.properties delete mode 100644 Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.xml diff --git a/.project b/.project index bd32f58..fa49362 100644 --- a/.project +++ b/.project @@ -14,4 +14,15 @@ org.eclipse.jdt.core.javanature + + + 1681308613588 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + diff --git a/Ejercicio1/.classpath b/Ejercicio1/.classpath index 5e8a55f..f0257c5 100644 --- a/Ejercicio1/.classpath +++ b/Ejercicio1/.classpath @@ -23,5 +23,22 @@ + + + + + + + + + + + + + + + + + diff --git a/Ejercicio1/.project b/Ejercicio1/.project index 680b8a0..5e526a0 100644 --- a/Ejercicio1/.project +++ b/Ejercicio1/.project @@ -20,4 +20,15 @@ org.eclipse.jdt.core.javanature org.eclipse.m2e.core.maven2Nature + + + 1681308613605 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + diff --git a/Ejercicio1/.settings/org.eclipse.jdt.apt.core.prefs b/Ejercicio1/.settings/org.eclipse.jdt.apt.core.prefs new file mode 100644 index 0000000..d4313d4 --- /dev/null +++ b/Ejercicio1/.settings/org.eclipse.jdt.apt.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.apt.aptEnabled=false diff --git a/Ejercicio1/.settings/org.eclipse.jdt.core.prefs b/Ejercicio1/.settings/org.eclipse.jdt.core.prefs index dfefb9a..70d61cf 100644 --- a/Ejercicio1/.settings/org.eclipse.jdt.core.prefs +++ b/Ejercicio1/.settings/org.eclipse.jdt.core.prefs @@ -106,5 +106,6 @@ org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.processAnnotations=disabled org.eclipse.jdt.core.compiler.release=disabled org.eclipse.jdt.core.compiler.source=1.8 diff --git a/Ejercicio1/target/classes/META-INF/MANIFEST.MF b/Ejercicio1/target/classes/META-INF/MANIFEST.MF deleted file mode 100644 index 558ccf1..0000000 --- a/Ejercicio1/target/classes/META-INF/MANIFEST.MF +++ /dev/null @@ -1,5 +0,0 @@ -Manifest-Version: 1.0 -Built-By: javie -Build-Jdk: 17.0.4.1 -Created-By: Maven Integration for Eclipse - diff --git a/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.properties b/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.properties deleted file mode 100644 index bb58a75..0000000 --- a/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.properties +++ /dev/null @@ -1,7 +0,0 @@ -#Generated by Maven Integration for Eclipse -#Wed Apr 12 14:56:07 CEST 2023 -m2e.projectLocation=C\:\\Users\\javie\\OneDrive\\Escritorio\\Bootcamp Fullstack Java T-Systems\\Repository\\UD22\\UD22\\Ejercicio1 -m2e.projectName=ta22 -groupId=22 -artifactId=ta22 -version=0.0.1-SNAPSHOT diff --git a/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.xml b/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.xml deleted file mode 100644 index 66c4e42..0000000 --- a/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - 4.0.0 - - 22 - ta22 - 0.0.1-SNAPSHOT - jar - - ta22 - http://maven.apache.org - - - UTF-8 - 1.8 - 1.8 - - - - - junit - junit - 3.8.1 - test - - - mysql - mysql-connector-java - 8.0.32 - - - From 3fc447af30bdeb165d035e5b766464d379575846 Mon Sep 17 00:00:00 2001 From: Joan Date: Wed, 12 Apr 2023 18:44:43 +0200 Subject: [PATCH 03/10] Table classes en proceso --- .../src/main/java/models/Attribute.java | 2 +- .../src/main/java/models/Connector.java | 28 ++++++++-------- Ejercicio1/src/main/java/models/DataBase.java | 32 +++++++++++++++++++ .../src/main/java/models/TablaCliente.java | 23 ------------- Ejercicio1/src/main/java/models/Table.java | 30 +++++++++-------- 5 files changed, 64 insertions(+), 51 deletions(-) create mode 100644 Ejercicio1/src/main/java/models/DataBase.java delete mode 100644 Ejercicio1/src/main/java/models/TablaCliente.java diff --git a/Ejercicio1/src/main/java/models/Attribute.java b/Ejercicio1/src/main/java/models/Attribute.java index 6994aa4..b7ce7a3 100644 --- a/Ejercicio1/src/main/java/models/Attribute.java +++ b/Ejercicio1/src/main/java/models/Attribute.java @@ -31,6 +31,6 @@ public class Attribute { @Override public String toString() { - return name + " " + type + type_cardinality + " " + others; + return name + " " + type + type_cardinality + " " + String.join(" ", others); } } diff --git a/Ejercicio1/src/main/java/models/Connector.java b/Ejercicio1/src/main/java/models/Connector.java index 22d3da5..b1fe97e 100644 --- a/Ejercicio1/src/main/java/models/Connector.java +++ b/Ejercicio1/src/main/java/models/Connector.java @@ -12,11 +12,9 @@ public class Connector { private static final String URL = Credenciales.URL; private static final String USER = Credenciales.USER; private static final String PASSWORD = Credenciales.PASSWORD; - private static Connection conexion = null; - // Create connection - public Connector() { + public static void openConnection() { try { Class.forName(DRIVER); conexion = DriverManager.getConnection(URL, USER, PASSWORD); @@ -26,9 +24,8 @@ public Connector() { System.out.println(ex); } } - - // Close connection - public void closeConnection() { + + public static void closeConnection() { try { conexion.close(); JOptionPane.showMessageDialog(null, "Se ha finalizado la conexion con el servidor"); @@ -38,7 +35,7 @@ public void closeConnection() { } // Create database - public void createDB(String dbName) { + public static void createDB(String dbName) { try { String kuery = " CREATE DATABASE IF NOT EXISTS " + dbName + " ;"; Statement st = conexion.createStatement(); @@ -51,16 +48,19 @@ public void createDB(String dbName) { } // Create table - public void createTable(String nombreBBDD, String nombreTabla, String tablaColum) { + public static void createTable(String nombreBBDD, String nombreTabla, String tablaColum) { try { String queryDb = "USE " + nombreBBDD + ";"; Statement stdb = conexion.createStatement(); stdb.executeUpdate(queryDb); String query = "CREATE TABLE IF NOT EXISTS " + nombreTabla + " (" + tablaColum + ");"; + System.out.println(query); Statement st = conexion.createStatement(); st.executeUpdate(query); + + System.out.println("Se ha creado la tabla " + nombreTabla + " correctamente"); } catch (SQLException ex) { Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); @@ -68,8 +68,8 @@ public void createTable(String nombreBBDD, String nombreTabla, String tablaColum } } - // Insert table - public void insert(String dbName, String tableName, String columns, String values) { + // Insert row to table table + public static void insert(String dbName, String tableName, String columns, String values) { try { String queryDb = "USE " + dbName + ";"; Statement stdb = conexion.createStatement(); @@ -86,8 +86,8 @@ public void insert(String dbName, String tableName, String columns, String value } } - // Select - public ResultSet select(String db, String table_name) { + // Select all rows from table + public static ResultSet select(String db, String table_name) { try { String queryDb = "USE " + db + ";"; Statement stdb = conexion.createStatement(); @@ -104,8 +104,8 @@ public ResultSet select(String db, String table_name) { } } - // Delete - public void delete(String table_name_columna, String columna, String campo) { + // Delete + public static void delete(String table_name_columna, String columna, String campo) { try { String query = "DELETE FROM " + table_name_columna + " WHERE " + columna + "= \"" + campo + "\""; Statement st = conexion.createStatement(); diff --git a/Ejercicio1/src/main/java/models/DataBase.java b/Ejercicio1/src/main/java/models/DataBase.java new file mode 100644 index 0000000..3ee54f2 --- /dev/null +++ b/Ejercicio1/src/main/java/models/DataBase.java @@ -0,0 +1,32 @@ +package models; + +public class DataBase { + + public static Table cliente; + public static String DBNAME = "proves_joan"; + //static public ArrayList tables; <- para futuros ejercicios con más de una tabla + + public static void init() { + Attribute[] attributes = { + new Attribute("id", "INT", "(11)", "NOT NULL AUTO_INCREMENT PRIMARY KEY"), + new Attribute("Nombre", "VARCHAR", "(250)", "NOT NULL"), + new Attribute("Apellido", "VARCHAR", "(250)", "NOT NULL"), + new Attribute("Direccion", "VARCHAR", "(250)", "NOT NULL"), + new Attribute("DNI", "VARCHAR", "(250)", "DEFAULT NULL"), + new Attribute("Fecha", "DATE", "", "DEFAULT NULL"), + }; + cliente = new Table("cliente", attributes, DBNAME); + + Connector.openConnection(); + Connector.createDB(DBNAME); + cliente.createTable(); + } + + + public static void main(String[] args) { + init(); + } + + + +} diff --git a/Ejercicio1/src/main/java/models/TablaCliente.java b/Ejercicio1/src/main/java/models/TablaCliente.java deleted file mode 100644 index f61bfce..0000000 --- a/Ejercicio1/src/main/java/models/TablaCliente.java +++ /dev/null @@ -1,23 +0,0 @@ -package models; - -// en futuros ejercicios esta clase podrá contener más de una tabla -public class TablaCliente { - public Table tabla; - - public TablaCliente() { - Attribute[] attributes = { - new Attribute("id", "INT", "(11)", "NOT NULL AUTO_INCREMENT PRIMARY KEY"), - new Attribute("Nombre", "VARCHAR", "(250)", "NOT NULL"), - new Attribute("Apellido", "VARCHAR", "(250)", "NOT NULL"), - new Attribute("Direccion", "VARCHAR", "(250)", "NOT NULL"), - new Attribute("DNI", "VARCHAR", "(250)", "DEFAULT NULL"), - new Attribute("fecha", "DATE", "", "DEFAULT NULL"), - }; - tabla = new Table("cliente", attributes); - tabla.createTable(); - } - - - - -} diff --git a/Ejercicio1/src/main/java/models/Table.java b/Ejercicio1/src/main/java/models/Table.java index 880e750..fb14e40 100644 --- a/Ejercicio1/src/main/java/models/Table.java +++ b/Ejercicio1/src/main/java/models/Table.java @@ -6,21 +6,25 @@ * usable para otros ejercicios similares */ public class Table { - private String name; - private Attribute[] attributes; - //TODO: foregin keys + public String name; + public Attribute[] attributes; + public final String DBNAME; - Table(String name, Attribute[] attributes) { - this.attributes = attributes; + Table(String name, Attribute[] attributes, String dbname) { this.name = name; + this.attributes = attributes; + this.DBNAME = dbname; } - public Attribute[] getAttributes() { - return attributes; - } - - public void createTable() { - - } - + /** + * This method create table "clientes". + */ + public void createTable() { + String[] attributeStrings = new String[attributes.length]; + for (int i = 0; i < attributes.length; i++) { + attributeStrings[i] = attributes[i].toString(); + } + Connector.createTable(DBNAME, name, String.join(", ", attributeStrings)); + } + } From 03ea428d83cf2e092c037873edef834fd5ca45fc Mon Sep 17 00:00:00 2001 From: Joan Date: Wed, 12 Apr 2023 19:04:27 +0200 Subject: [PATCH 04/10] en proceso... --- Ejercicio1/src/main/java/models/Cliente.java | 9 ++++----- Ejercicio1/src/main/java/models/Table.java | 7 +++++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/Ejercicio1/src/main/java/models/Cliente.java b/Ejercicio1/src/main/java/models/Cliente.java index c8402a1..be06d27 100644 --- a/Ejercicio1/src/main/java/models/Cliente.java +++ b/Ejercicio1/src/main/java/models/Cliente.java @@ -21,7 +21,6 @@ public class Cliente { private int dni; private Date fecha; - private static final Connector CONNEXION = new Connector(); private static final String DBNAME = "servicios"; private static final String TBNAME = "clientes"; @@ -48,14 +47,14 @@ public Cliente(int id, String nombre, String apellido, String direccion, int dni * This method create de database if exists. */ public void createDatabase() { - CONNEXION.createDB(DBNAME); + Connector.createDB(DBNAME); } /** * This method create table "clientes". */ public void createTable() { - CONNEXION.createTable(DBNAME, TBNAME, + Connector.createTable(DBNAME, TBNAME, "id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY," + "nombre VARCHAR(250) NOT NULL," + "apellido VARCHAR(250) NOT NULL," @@ -68,7 +67,7 @@ public void createTable() { * This method insert data into database. */ public void insert() { - CONNEXION.insert(DBNAME, TBNAME, + Connector.insert(DBNAME, TBNAME, "nombre, apellido, direccion, dni, fecha", "'" + this.nombre + "', '" + this.apellido + "', '" + this.direccion + "', " + this.dni + ", '" + this.fecha + "'"); } @@ -77,7 +76,7 @@ public void insert() { * This method select data. */ public List select() { - ResultSet resultSet = CONNEXION.select(DBNAME,TBNAME); + ResultSet resultSet = Connector.select(DBNAME,TBNAME); List clientes = new ArrayList<>(); try { while (resultSet.next()) { diff --git a/Ejercicio1/src/main/java/models/Table.java b/Ejercicio1/src/main/java/models/Table.java index fb14e40..a4bc43a 100644 --- a/Ejercicio1/src/main/java/models/Table.java +++ b/Ejercicio1/src/main/java/models/Table.java @@ -26,5 +26,12 @@ public void createTable() { } Connector.createTable(DBNAME, name, String.join(", ", attributeStrings)); } + + /*public void insert(String[]) { + Connector.insert(DBNAME, name, + "nombre, apellido, direccion, dni, fecha", + ); + + }*/ } From 0d3afd201913f462a76d887b4d25068c5e804944 Mon Sep 17 00:00:00 2001 From: Joan Date: Wed, 12 Apr 2023 19:43:47 +0200 Subject: [PATCH 05/10] Table.insert() et al --- Ejercicio1/src/main/java/models/Attribute.java | 13 +++---------- Ejercicio1/src/main/java/models/Connector.java | 6 +++--- Ejercicio1/src/main/java/models/DataBase.java | 17 +++++++++-------- Ejercicio1/src/main/java/models/Table.java | 9 +++------ 4 files changed, 18 insertions(+), 27 deletions(-) diff --git a/Ejercicio1/src/main/java/models/Attribute.java b/Ejercicio1/src/main/java/models/Attribute.java index b7ce7a3..a55a973 100644 --- a/Ejercicio1/src/main/java/models/Attribute.java +++ b/Ejercicio1/src/main/java/models/Attribute.java @@ -5,11 +5,10 @@ public class Attribute { public String name; public String type; - public String type_cardinality = ""; public String[] others = {}; // example: JEFE CHARVAR(30) NOT NULL REFERENCES EMPLEADO - // name="ID", type="CHARVAR", type_cardinality="(30)", + // name="JEFE", type="CHARVAR", type_cardinality="(30)", // others=["NOT", "NULL", "REFERENCES", "EMPLEADO"] @@ -17,20 +16,14 @@ public class Attribute { this.name = name; this.type = type; } - Attribute(String name, String type, String type_cardinality) { + Attribute(String name, String type, String others) { this.name = name; this.type = type; - this.type_cardinality = type_cardinality; - } - Attribute(String name, String type, String type_cardinality, String others) { - this.name = name; - this.type = type; - this.type_cardinality = type_cardinality; this.others = others.split(others); } @Override public String toString() { - return name + " " + type + type_cardinality + " " + String.join(" ", others); + return name + " " + type + " " + String.join(" ", others); } } diff --git a/Ejercicio1/src/main/java/models/Connector.java b/Ejercicio1/src/main/java/models/Connector.java index b1fe97e..cf4e167 100644 --- a/Ejercicio1/src/main/java/models/Connector.java +++ b/Ejercicio1/src/main/java/models/Connector.java @@ -59,8 +59,6 @@ public static void createTable(String nombreBBDD, String nombreTabla, String tab Statement st = conexion.createStatement(); st.executeUpdate(query); - - System.out.println("Se ha creado la tabla " + nombreTabla + " correctamente"); } catch (SQLException ex) { Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); @@ -76,13 +74,15 @@ public static void insert(String dbName, String tableName, String columns, Strin stdb.executeUpdate(queryDb); String query = "INSERT INTO " + tableName + " (" + columns + ") VALUES (" + values + ");"; + System.out.println(query); Statement st = conexion.createStatement(); st.executeUpdate(query); System.out.println("Datos insertados correctamente en la tabla " + tableName); } catch (SQLException ex) { Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); - JOptionPane.showMessageDialog(null, "Error insertando datos en la tabla " + tableName); + JOptionPane.showMessageDialog(null, + "Error insertando datos en la tabla " + tableName + ": "+ex.getMessage()); } } diff --git a/Ejercicio1/src/main/java/models/DataBase.java b/Ejercicio1/src/main/java/models/DataBase.java index 3ee54f2..78d2857 100644 --- a/Ejercicio1/src/main/java/models/DataBase.java +++ b/Ejercicio1/src/main/java/models/DataBase.java @@ -4,18 +4,17 @@ public class DataBase { public static Table cliente; public static String DBNAME = "proves_joan"; - //static public ArrayList
tables; <- para futuros ejercicios con más de una tabla public static void init() { Attribute[] attributes = { - new Attribute("id", "INT", "(11)", "NOT NULL AUTO_INCREMENT PRIMARY KEY"), - new Attribute("Nombre", "VARCHAR", "(250)", "NOT NULL"), - new Attribute("Apellido", "VARCHAR", "(250)", "NOT NULL"), - new Attribute("Direccion", "VARCHAR", "(250)", "NOT NULL"), - new Attribute("DNI", "VARCHAR", "(250)", "DEFAULT NULL"), - new Attribute("Fecha", "DATE", "", "DEFAULT NULL"), + new Attribute("id", "INT(11)", "NOT NULL AUTO_INCREMENT PRIMARY KEY"), + new Attribute("Nombre", "VARCHAR(250)", "NOT NULL"), + new Attribute("Apellido", "VARCHAR(250)", "NOT NULL"), + new Attribute("Direccion", "VARCHAR(250)", "NOT NULL"), + new Attribute("DNI", "VARCHAR(250)", "DEFAULT NULL"), + new Attribute("Fecha", "DATE", "DEFAULT NULL"), }; - cliente = new Table("cliente", attributes, DBNAME); + cliente = new Table("clientes", attributes, DBNAME); Connector.openConnection(); Connector.createDB(DBNAME); @@ -25,6 +24,8 @@ public static void init() { public static void main(String[] args) { init(); + cliente.insert(new String[]{"Nombre", "Apellido", "Direccion"}, + new String[]{"joan","lapeyra","manila"}); } diff --git a/Ejercicio1/src/main/java/models/Table.java b/Ejercicio1/src/main/java/models/Table.java index a4bc43a..9c7a72e 100644 --- a/Ejercicio1/src/main/java/models/Table.java +++ b/Ejercicio1/src/main/java/models/Table.java @@ -27,11 +27,8 @@ public void createTable() { Connector.createTable(DBNAME, name, String.join(", ", attributeStrings)); } - /*public void insert(String[]) { - Connector.insert(DBNAME, name, - "nombre, apellido, direccion, dni, fecha", - ); - - }*/ + public void insert(String[] keys, String[] values) { + Connector.insert(DBNAME, name, String.join(", ", keys), "'"+String.join("', '", values)+"'"); + } } From 4a258018cbf2a87b6393d9868e436b45e9cf5291 Mon Sep 17 00:00:00 2001 From: Joan Date: Wed, 12 Apr 2023 21:02:23 +0200 Subject: [PATCH 06/10] =?UTF-8?q?nuevo=20m=C3=A9todo=20funciona=20para=20i?= =?UTF-8?q?nsert=20y=20select?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Ejercicio1/src/main/java/app1Main/App.java | 2 + .../controller/Cliente_InsertController.java | 7 +-- .../controller/Cliente_ListController.java | 18 +++----- .../src/main/java/models/Attribute.java | 12 ++--- .../src/main/java/models/Connector.java | 10 +++-- Ejercicio1/src/main/java/models/DataBase.java | 10 +++-- Ejercicio1/src/main/java/models/Table.java | 44 ++++++++++++++++--- .../META-INF/maven/22/ta22/pom.properties | 7 --- 8 files changed, 68 insertions(+), 42 deletions(-) delete mode 100644 Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.properties diff --git a/Ejercicio1/src/main/java/app1Main/App.java b/Ejercicio1/src/main/java/app1Main/App.java index 4389b2d..bc09aa8 100644 --- a/Ejercicio1/src/main/java/app1Main/App.java +++ b/Ejercicio1/src/main/java/app1Main/App.java @@ -2,6 +2,7 @@ import javax.swing.*; import controller.*; +import models.DataBase; import views.Cliente_InsertView; import views.Cliente_ListView; @@ -24,6 +25,7 @@ public static void main( String[] args ) { catch (IllegalAccessException e) { } + DataBase.init(); Cliente_InsertView insertView = new Cliente_InsertView(); Cliente_InsertController controllerInsert = new Cliente_InsertController(insertView); controllerInsert.initVista(); diff --git a/Ejercicio1/src/main/java/controller/Cliente_InsertController.java b/Ejercicio1/src/main/java/controller/Cliente_InsertController.java index 028aa40..88e8163 100644 --- a/Ejercicio1/src/main/java/controller/Cliente_InsertController.java +++ b/Ejercicio1/src/main/java/controller/Cliente_InsertController.java @@ -46,14 +46,15 @@ public void actionPerformed(ActionEvent e) { try { LocalDate fechaLocal = LocalDate.parse(fechaTexto, formatoFecha); // Analizar el texto de la fecha y crear un objeto LocalDate a partir de ella java.sql.Date fecha = java.sql.Date.valueOf(fechaLocal); // Convertir el objeto LocalDate a un objeto java.sql.Date - cliente = new Cliente(0, nombre, apellidos, direccion, dni, fecha); + DataBase.cliente.insert( + new String[]{"Nombre", "Apellido", "Direccion", "DNI", "Fecha"}, + new String[]{nombre,apellidos,direccion,Integer.toString(dni),fecha.toString()} + ); } catch (DateTimeParseException ex) { ex.printStackTrace(); } - cliente.insert(); - JOptionPane.showMessageDialog(insert, "Cliente creado correctamente."); insert.dispose(); } diff --git a/Ejercicio1/src/main/java/controller/Cliente_ListController.java b/Ejercicio1/src/main/java/controller/Cliente_ListController.java index b736437..d0162ca 100644 --- a/Ejercicio1/src/main/java/controller/Cliente_ListController.java +++ b/Ejercicio1/src/main/java/controller/Cliente_ListController.java @@ -5,6 +5,7 @@ import java.util.List; import javax.swing.JFrame; import models.Cliente; +import models.DataBase; import views.Cliente_InsertView; import views.Cliente_ListView; import javax.swing.table.DefaultTableModel; @@ -32,19 +33,10 @@ public void initVista() { } public DefaultTableModel list() { - List clientes = cliente.select(); - DefaultTableModel model = new DefaultTableModel( - new String[]{"ID", "Nombre", "Apellido", "Dirección", "DNI", "Fecha"}, 0); - - for (Cliente c : clientes) { - Object[] fila = new Object[6]; - fila[0] = c.getId(); - fila[1] = c.getNombre(); - fila[2] = c.getApellido(); - fila[3] = c.getDireccion(); - fila[4] = c.getDni(); - fila[5] = c.getFecha(); - model.addRow(fila); + List rows = DataBase.cliente.select(); + DefaultTableModel model = new DefaultTableModel(DataBase.cliente.getAttributeNames(), 0); + for (String[] row : rows) { + model.addRow(row); } return model; } diff --git a/Ejercicio1/src/main/java/models/Attribute.java b/Ejercicio1/src/main/java/models/Attribute.java index a55a973..ed82e06 100644 --- a/Ejercicio1/src/main/java/models/Attribute.java +++ b/Ejercicio1/src/main/java/models/Attribute.java @@ -1,11 +1,13 @@ package models; - -// esta clase representa el atributo de una tabla de una BD +/** + * @author Joan + * esta clase representa el atributo de una tabla de una BD + */ public class Attribute { public String name; public String type; - public String[] others = {}; + public String others = ""; // example: JEFE CHARVAR(30) NOT NULL REFERENCES EMPLEADO // name="JEFE", type="CHARVAR", type_cardinality="(30)", @@ -19,11 +21,11 @@ public class Attribute { Attribute(String name, String type, String others) { this.name = name; this.type = type; - this.others = others.split(others); + this.others = others; } @Override public String toString() { - return name + " " + type + " " + String.join(" ", others); + return name + " " + type + " " + others; } } diff --git a/Ejercicio1/src/main/java/models/Connector.java b/Ejercicio1/src/main/java/models/Connector.java index cf4e167..8de2ba7 100644 --- a/Ejercicio1/src/main/java/models/Connector.java +++ b/Ejercicio1/src/main/java/models/Connector.java @@ -37,10 +37,10 @@ public static void closeConnection() { // Create database public static void createDB(String dbName) { try { - String kuery = " CREATE DATABASE IF NOT EXISTS " + dbName + " ;"; + String query = " CREATE DATABASE IF NOT EXISTS " + dbName + " ;"; Statement st = conexion.createStatement(); - System.out.println(kuery); - st.executeUpdate(kuery); + System.out.println(query); + st.executeUpdate(query); System.out.println("Se ha creado la base de datos " + dbName + " correctamente"); } catch (SQLException ex) { Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); @@ -94,6 +94,7 @@ public static ResultSet select(String db, String table_name) { stdb.executeUpdate(queryDb); String query = "SELECT * FROM " + table_name; + System.out.println(query); Statement st = conexion.createStatement(); return st.executeQuery(query); @@ -107,7 +108,8 @@ public static ResultSet select(String db, String table_name) { // Delete public static void delete(String table_name_columna, String columna, String campo) { try { - String query = "DELETE FROM " + table_name_columna + " WHERE " + columna + "= \"" + campo + "\""; + String query = "DELETE FROM " + table_name_columna + " WHERE " + columna + " = " + campo; + System.out.println(query); Statement st = conexion.createStatement(); st.executeUpdate(query); diff --git a/Ejercicio1/src/main/java/models/DataBase.java b/Ejercicio1/src/main/java/models/DataBase.java index 78d2857..6b88ddd 100644 --- a/Ejercicio1/src/main/java/models/DataBase.java +++ b/Ejercicio1/src/main/java/models/DataBase.java @@ -1,9 +1,12 @@ package models; +/** + * @author Joan + */ public class DataBase { public static Table cliente; - public static String DBNAME = "proves_joan"; + public static String DBNAME = "services"; public static void init() { Attribute[] attributes = { @@ -14,7 +17,7 @@ public static void init() { new Attribute("DNI", "VARCHAR(250)", "DEFAULT NULL"), new Attribute("Fecha", "DATE", "DEFAULT NULL"), }; - cliente = new Table("clientes", attributes, DBNAME); + cliente = new Table("clientes", attributes, new int[]{0}, DBNAME); Connector.openConnection(); Connector.createDB(DBNAME); @@ -25,7 +28,8 @@ public static void init() { public static void main(String[] args) { init(); cliente.insert(new String[]{"Nombre", "Apellido", "Direccion"}, - new String[]{"joan","lapeyra","manila"}); + new String[]{"anna","lapeyra","manila"}); + cliente.select(); } diff --git a/Ejercicio1/src/main/java/models/Table.java b/Ejercicio1/src/main/java/models/Table.java index 9c7a72e..f717ede 100644 --- a/Ejercicio1/src/main/java/models/Table.java +++ b/Ejercicio1/src/main/java/models/Table.java @@ -1,24 +1,36 @@ package models; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; -/* +/** + * @author Joan * Esta clase es una forma genérica de representar tablas SQL * usable para otros ejercicios similares */ public class Table { public String name; public Attribute[] attributes; + public int[] primary_key; //indexs de attributes que son la primary key public final String DBNAME; - Table(String name, Attribute[] attributes, String dbname) { + public Table(String name, Attribute[] attributes, int[] primary_key, String dbname) { this.name = name; this.attributes = attributes; + this.primary_key = primary_key; this.DBNAME = dbname; } + + public String[] getAttributeNames() { + String[] names = new String[attributes.length]; + for (int i = 0; i < names.length; i++) { + names[i] = attributes[i].name; + } + return names; + } - /** - * This method create table "clientes". - */ public void createTable() { String[] attributeStrings = new String[attributes.length]; for (int i = 0; i < attributes.length; i++) { @@ -27,8 +39,26 @@ public void createTable() { Connector.createTable(DBNAME, name, String.join(", ", attributeStrings)); } - public void insert(String[] keys, String[] values) { - Connector.insert(DBNAME, name, String.join(", ", keys), "'"+String.join("', '", values)+"'"); + public void insert(String[] columns, String[] values) { + Connector.insert(DBNAME, name, String.join(", ", columns), "'"+String.join("', '", values)+"'"); } + + public List select() { + ResultSet resultSet = Connector.select(DBNAME,name); + List rows = new ArrayList<>(); + try { + while (resultSet.next()) { + String[] row = new String[attributes.length]; + for (int i = 0; i < attributes.length; i++) { + row[i] = resultSet.getString(attributes[i].name); + } + rows.add(row); + } + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + System.out.println("Error en la conversión de resultados a objetos Cliente"); + } + return rows; + } } diff --git a/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.properties b/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.properties deleted file mode 100644 index ee5b32e..0000000 --- a/Ejercicio1/target/classes/META-INF/maven/22/ta22/pom.properties +++ /dev/null @@ -1,7 +0,0 @@ -#Generated by Maven Integration for Eclipse -#Wed Apr 12 18:35:04 CEST 2023 -m2e.projectLocation=C\:\\Users\\paula\\eclipse-workspace\\UD22\\Ejercicio1 -m2e.projectName=ta22 -groupId=22 -artifactId=ta22 -version=0.0.1-SNAPSHOT From ec2a6a2cf73cfd12530811b7adc306d835d3a20c Mon Sep 17 00:00:00 2001 From: Joan Date: Thu, 13 Apr 2023 10:17:41 +0200 Subject: [PATCH 07/10] dbname servicios --- Ejercicio1/src/main/java/models/DataBase.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Ejercicio1/src/main/java/models/DataBase.java b/Ejercicio1/src/main/java/models/DataBase.java index 6b88ddd..4752899 100644 --- a/Ejercicio1/src/main/java/models/DataBase.java +++ b/Ejercicio1/src/main/java/models/DataBase.java @@ -6,7 +6,7 @@ public class DataBase { public static Table cliente; - public static String DBNAME = "services"; + public static String DBNAME = "servicios"; public static void init() { Attribute[] attributes = { From 5ada580f4e53cb8b63bf8bb471ce856cda5c6333 Mon Sep 17 00:00:00 2001 From: Joan Date: Thu, 13 Apr 2023 17:45:02 +0200 Subject: [PATCH 08/10] ejercicio 1 terminado --- Ejercicio1/src/main/java/app1Main/App.java | 14 +-- .../controller/Cliente_InsertController.java | 69 ------------- .../controller/Cliente_ListController.java | 50 ---------- .../controller/EditCliente_Controller.java | 99 +++++++++++++++++++ ...exController.java => IndexController.java} | 31 ++---- .../main/java/controller/ListController.java | 83 ++++++++++++++++ .../src/main/java/models/Connector.java | 43 +++++--- Ejercicio1/src/main/java/models/Table.java | 27 +++++ ..._InsertView.java => EditCliente_View.java} | 32 +++--- .../{Cliente_Index.java => IndexView.java} | 7 +- .../{Cliente_ListView.java => ListView.java} | 22 +++-- 11 files changed, 279 insertions(+), 198 deletions(-) delete mode 100644 Ejercicio1/src/main/java/controller/Cliente_InsertController.java delete mode 100644 Ejercicio1/src/main/java/controller/Cliente_ListController.java create mode 100644 Ejercicio1/src/main/java/controller/EditCliente_Controller.java rename Ejercicio1/src/main/java/controller/{Cliente_IndexController.java => IndexController.java} (59%) create mode 100644 Ejercicio1/src/main/java/controller/ListController.java rename Ejercicio1/src/main/java/views/{Cliente_InsertView.java => EditCliente_View.java} (80%) rename Ejercicio1/src/main/java/views/{Cliente_Index.java => IndexView.java} (92%) rename Ejercicio1/src/main/java/views/{Cliente_ListView.java => ListView.java} (52%) diff --git a/Ejercicio1/src/main/java/app1Main/App.java b/Ejercicio1/src/main/java/app1Main/App.java index 4065948..30f5a4e 100644 --- a/Ejercicio1/src/main/java/app1Main/App.java +++ b/Ejercicio1/src/main/java/app1Main/App.java @@ -2,10 +2,7 @@ import javax.swing.*; import controller.*; -import views.Cliente_Index; import models.DataBase; -import views.Cliente_InsertView; -import views.Cliente_ListView; /** * @author Javier @@ -26,14 +23,7 @@ public static void main( String[] args ) { catch (IllegalAccessException e) { } -// Cliente_InsertView insertView = new Cliente_InsertView(); -// Cliente_InsertController controllerInsert = new Cliente_InsertController(insertView); -// controllerInsert.initVista(); -// Cliente_ListView listView = new Cliente_ListView(); -// Cliente_ListController controller = new Cliente_ListController(listView); -// controller.initVista(); - Cliente_Index insertIndex = new Cliente_Index(); - Cliente_IndexController controller = new Cliente_IndexController(insertIndex); - controller.initVista(); + DataBase.init(); + new ListController(); } } diff --git a/Ejercicio1/src/main/java/controller/Cliente_InsertController.java b/Ejercicio1/src/main/java/controller/Cliente_InsertController.java deleted file mode 100644 index 88e8163..0000000 --- a/Ejercicio1/src/main/java/controller/Cliente_InsertController.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * - */ -package controller; - -import java.awt.event.*; -import java.sql.Date; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.ZoneId; -import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeParseException; - -import javax.swing.*; - -import models.*; -import views.*; - -/** - * @author Javier - * - */ -public class Cliente_InsertController implements ActionListener { - - private Cliente cliente; - private Cliente_InsertView insert; - - - public Cliente_InsertController(Cliente_InsertView insert) { - this.insert = insert; - this.insert.crear.addActionListener(this); - } - - @Override - public void actionPerformed(ActionEvent e) { - - String nombre = insert.nombre.getText(); - String apellidos = insert.apellidos.getText(); - String direccion = insert.direccion.getText(); - int dni = Integer.parseInt(insert.dni.getText()); - - String fechaTexto = insert.fecha.getText(); // Obtener el texto del campo de fecha - DateTimeFormatter formatoFecha = DateTimeFormatter.ofPattern("yyyy-MM-dd");//establecer el formato - - try { - LocalDate fechaLocal = LocalDate.parse(fechaTexto, formatoFecha); // Analizar el texto de la fecha y crear un objeto LocalDate a partir de ella - java.sql.Date fecha = java.sql.Date.valueOf(fechaLocal); // Convertir el objeto LocalDate a un objeto java.sql.Date - DataBase.cliente.insert( - new String[]{"Nombre", "Apellido", "Direccion", "DNI", "Fecha"}, - new String[]{nombre,apellidos,direccion,Integer.toString(dni),fecha.toString()} - ); - } catch (DateTimeParseException ex) { - ex.printStackTrace(); - } - - - JOptionPane.showMessageDialog(insert, "Cliente creado correctamente."); - insert.dispose(); - } - - public void initVista() { - - insert.setTitle("Nuevo cliente"); - insert.setBounds(300, 300, 354, 351); - insert.setLocationRelativeTo(null); - insert.setVisible(true); - } -} diff --git a/Ejercicio1/src/main/java/controller/Cliente_ListController.java b/Ejercicio1/src/main/java/controller/Cliente_ListController.java deleted file mode 100644 index d0162ca..0000000 --- a/Ejercicio1/src/main/java/controller/Cliente_ListController.java +++ /dev/null @@ -1,50 +0,0 @@ -package controller; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.util.List; -import javax.swing.JFrame; -import models.Cliente; -import models.DataBase; -import views.Cliente_InsertView; -import views.Cliente_ListView; -import javax.swing.table.DefaultTableModel; - - -public class Cliente_ListController implements ActionListener { - - private Cliente cliente; - private Cliente_ListView list; - - public Cliente_ListController(Cliente_ListView list) { - this.cliente = new Cliente(); - this.list = list; - this.list.add.addActionListener(this); - } - - public void initVista() { - list.setTitle("Lista de clientes"); - list.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - list.setBounds(300, 300, 450, 351); - list.setLocationRelativeTo(null); - list.setVisible(true); - - list.table.setModel(list()); - } - - public DefaultTableModel list() { - List rows = DataBase.cliente.select(); - DefaultTableModel model = new DefaultTableModel(DataBase.cliente.getAttributeNames(), 0); - for (String[] row : rows) { - model.addRow(row); - } - return model; - } - - @Override - public void actionPerformed(ActionEvent e) { - Cliente_InsertView insertView = new Cliente_InsertView(); - Cliente_InsertController controller = new Cliente_InsertController(insertView); - controller.initVista(); - } -} diff --git a/Ejercicio1/src/main/java/controller/EditCliente_Controller.java b/Ejercicio1/src/main/java/controller/EditCliente_Controller.java new file mode 100644 index 0000000..51a68c7 --- /dev/null +++ b/Ejercicio1/src/main/java/controller/EditCliente_Controller.java @@ -0,0 +1,99 @@ +/** + * + */ +package controller; + +import java.awt.event.*; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +import javax.swing.*; + +import javafx.scene.chart.PieChart.Data; +import models.*; +import views.*; + +/** + * @author Joan + * Esta clase añade (insert) o modifica (update) un elemento de la tabla cliente + * Si elementToUpdate==null, inserta un nuevo elemento + * Si no, modifica el elemento cuyos campos son elementToUpdate + */ +public class EditCliente_Controller implements ActionListener { + + private EditCliente_View view; + private ListController listController; + private String[] elementToUpdate = null; + + // insert cliente + public EditCliente_Controller(ListController listController) { + this.listController = listController; + initVista(); + view.setTitle("Nuevo cliente"); + view.labelTitle.setText("NUEVO CLIENTE"); + view.button.setText("Añadir"); + } + + // update cliente + public EditCliente_Controller(ListController listController, String[] elementToUpdate) { + this.listController = listController; + this.elementToUpdate = elementToUpdate; + initVista(); + view.setTitle("Modificar cliente"); + view.labelTitle.setText("MODIFICAR CLIENTE"); + view.button.setText("Modificar"); + + view.nombre.setText(elementToUpdate[1]); + view.apellidos.setText(elementToUpdate[2]); + view.direccion.setText(elementToUpdate[3]); + view.dni.setText(elementToUpdate[4]); + view.fecha.setText(elementToUpdate[5]); + } + + public void initVista() { + view = new EditCliente_View(); + view.button.addActionListener(this); + view.setBounds(300, 300, 354, 351); + view.setLocationRelativeTo(null); + view.setVisible(true); + } + + @Override + public void actionPerformed(ActionEvent e) { + String nombre = view.nombre.getText(); + String apellidos = view.apellidos.getText(); + String direccion = view.direccion.getText(); + int dni = 0; + java.sql.Date fecha = null; + + try { + dni = Integer.parseInt(view.dni.getText()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(view, "El DNI debe ser un número entero"); + return; + } + try { + String fechaTexto = view.fecha.getText(); // Obtener el texto del campo de fecha + DateTimeFormatter formatoFecha = DateTimeFormatter.ofPattern("yyyy-MM-dd");//establecer el formato + LocalDate fechaLocal = LocalDate.parse(fechaTexto, formatoFecha); // Analizar el texto de la fecha y crear un objeto LocalDate a partir de ella + fecha = java.sql.Date.valueOf(fechaLocal); // Convertir el objeto LocalDate a un objeto java.sql.Date + } catch (Exception ex) { + JOptionPane.showMessageDialog(view, "El formato de la fecha es incorrecto (formato deseado: aaaa-mm-dd)"); + return; + } + + String[] columns = {"Nombre", "Apellido", "Direccion", "DNI", "Fecha"}; + String[] values = {nombre,apellidos,direccion,Integer.toString(dni),fecha.toString()}; + if (elementToUpdate == null) { + DataBase.cliente.insert(columns, values); + } + else { + DataBase.cliente.update(elementToUpdate, columns, values); + } + listController.refreshList(); + view.dispose(); + + } + + +} diff --git a/Ejercicio1/src/main/java/controller/Cliente_IndexController.java b/Ejercicio1/src/main/java/controller/IndexController.java similarity index 59% rename from Ejercicio1/src/main/java/controller/Cliente_IndexController.java rename to Ejercicio1/src/main/java/controller/IndexController.java index 95d020b..ea1f205 100644 --- a/Ejercicio1/src/main/java/controller/Cliente_IndexController.java +++ b/Ejercicio1/src/main/java/controller/IndexController.java @@ -3,26 +3,18 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import javax.swing.JButton; import javax.swing.JFrame; -import javax.swing.JPanel; import javax.swing.border.EmptyBorder; -import models.Cliente; -import views.Cliente_Index; -import views.Cliente_InsertView; -import views.Cliente_ListView; +import views.IndexView; -public class Cliente_IndexController implements ActionListener{ +public class IndexController implements ActionListener{ - private Cliente cliente; - private Cliente_Index indice; - private Cliente_InsertView insertView; + private IndexView indice; - public Cliente_IndexController(Cliente_Index indice) { - this.cliente = new Cliente(); + public IndexController(IndexView indice) { this.indice = indice; this.indice.nuevoCliente.addActionListener(this); this.indice.editarCliente.addActionListener(this); @@ -36,29 +28,20 @@ public void initVista() { indice.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); indice.setVisible(true); - - } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == indice.nuevoCliente) { // Crear y mostrar la vista de inserción de cliente - Cliente_InsertView insertView = new Cliente_InsertView(); - Cliente_InsertController insertController = new Cliente_InsertController(insertView); - insertController.initVista(); + //EditCliente_Controller insertController = new EditCliente_Controller(); + //insertController.initVista(); } else if (e.getSource() == indice.verCliente) { // Crear y mostrar la vista de visualización de clientes - Cliente_ListView listView = new Cliente_ListView(); - Cliente_ListController listController = new Cliente_ListController(listView); + ListController listController = new ListController(); listController.initVista(); } - - - - - } } diff --git a/Ejercicio1/src/main/java/controller/ListController.java b/Ejercicio1/src/main/java/controller/ListController.java new file mode 100644 index 0000000..8708abf --- /dev/null +++ b/Ejercicio1/src/main/java/controller/ListController.java @@ -0,0 +1,83 @@ +package controller; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.List; +import models.DataBase; +import views.ListView; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.table.DefaultTableModel; + + + +public class ListController implements ActionListener { + + private ListView view; + + public ListController() { + view = new ListView(); + view.insert.addActionListener(this); + view.delete.addActionListener(this); + view.update.addActionListener(this); + initVista(); + refreshList(); + } + + public void initVista() { + view.setTitle("Lista de clientes"); + view.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + view.setBounds(300, 300, 450, 351); + view.setLocationRelativeTo(null); + view.setVisible(true); + } + + public void refreshList() { + view.table.setModel(list()); + } + + private DefaultTableModel list() { + List rows = DataBase.cliente.select(); + DefaultTableModel model = new DefaultTableModel(DataBase.cliente.getAttributeNames(), 0); + for (String[] row : rows) { + model.addRow(row); + } + return model; + } + + private String[] getRowValues() { + int row = view.table.getSelectedRow(); + if (row == -1) { + JOptionPane.showMessageDialog(view, "Seleccione una fila"); + return null; + } + int n = view.table.getColumnCount(); + String[] values = new String[n]; + for (int i = 0; i < n; i++) { + values[i] = view.table.getValueAt(row, i).toString(); + } + return values; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == view.insert) { + new EditCliente_Controller(this); + } + else if (e.getSource() == view.delete) { + String[] row_values = getRowValues(); + if (row_values != null) { + if (0 == JOptionPane.showConfirmDialog(view, "¿Está seguro de que quiere eliminar este cliente?")) { + DataBase.cliente.delete(row_values); + refreshList(); + } + } + } + else if (e.getSource() == view.update) { + String[] row_values = getRowValues(); + if (row_values != null) { + new EditCliente_Controller(this, row_values); + } + } + } +} diff --git a/Ejercicio1/src/main/java/models/Connector.java b/Ejercicio1/src/main/java/models/Connector.java index 9f7105c..4430c8b 100644 --- a/Ejercicio1/src/main/java/models/Connector.java +++ b/Ejercicio1/src/main/java/models/Connector.java @@ -41,7 +41,7 @@ public static void createDB(String dbName) { Statement st = conexion.createStatement(); System.out.println(query); st.executeUpdate(query); - System.out.println("Se ha creado la base de datos " + dbName + " correctamente"); + System.out.println("\tSe ha creado la base de datos " + dbName + " correctamente"); } catch (SQLException ex) { Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); } @@ -55,12 +55,11 @@ public static void createTable(String nombreBBDD, String nombreTabla, String tab stdb.executeUpdate(queryDb); String query = "CREATE TABLE IF NOT EXISTS " + nombreTabla + " (" + tablaColum + ");"; - System.out.println(query); Statement st = conexion.createStatement(); System.out.println(query); st.executeUpdate(query); - System.out.println("Se ha creado la tabla " + nombreTabla + " correctamente"); + System.out.println("\tSe ha creado la tabla " + nombreTabla + " correctamente"); } catch (SQLException ex) { Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); JOptionPane.showMessageDialog(null, "Error creando la tabla " + nombreTabla); @@ -75,16 +74,15 @@ public static void insert(String dbName, String tableName, String columns, Strin stdb.executeUpdate(queryDb); String query = "INSERT INTO " + tableName + " (" + columns + ") VALUES (" + values + ");"; - System.out.println(query); Statement st = conexion.createStatement(); System.out.println(query); st.executeUpdate(query); - System.out.println("Datos insertados correctamente en la tabla " + tableName); + System.out.println("\tDatos insertados correctamente en la tabla " + tableName); } catch (SQLException ex) { - Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); - JOptionPane.showMessageDialog(null, - "Error insertando datos en la tabla " + tableName + ": "+ex.getMessage()); + //Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error insertando datos en la tabla"); } } @@ -96,23 +94,44 @@ public static ResultSet select(String db, String table_name) { stdb.executeUpdate(queryDb); String query = "SELECT * FROM " + table_name; - System.out.println(query); Statement st = conexion.createStatement(); System.out.println(query); return st.executeQuery(query); } catch (SQLException ex) { System.out.println(ex.getMessage()); - System.out.println("Error en la adquisicion de datos"); + JOptionPane.showMessageDialog(null, "Error en la adquisicion de datos"); return null; } } // Delete - public static void delete(String table_name_columna, String columna, String campo) { + public static void delete(String db, String table_name, String column, String value) { try { - String query = "DELETE FROM " + table_name_columna + " WHERE " + columna + " = " + campo; + String queryDb = "USE " + db + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "DELETE FROM " + table_name + " WHERE " + column + " = " + value; + Statement st = conexion.createStatement(); System.out.println(query); + st.executeUpdate(query); + + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error borrando el registro especificado"); + } + } + + // Delete + public static void update(String db, String table_name, String column, String value, String changes) { + try { + String queryDb = "USE " + db + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "UPDATE " + table_name + " SET " + changes + + " WHERE " + column + " = " + value + " "; Statement st = conexion.createStatement(); System.out.println(query); st.executeUpdate(query); diff --git a/Ejercicio1/src/main/java/models/Table.java b/Ejercicio1/src/main/java/models/Table.java index f717ede..5c5d16a 100644 --- a/Ejercicio1/src/main/java/models/Table.java +++ b/Ejercicio1/src/main/java/models/Table.java @@ -23,6 +23,7 @@ public Table(String name, Attribute[] attributes, int[] primary_key, String dbna this.DBNAME = dbname; } + // retorna un array con los nombres de los atributos public String[] getAttributeNames() { String[] names = new String[attributes.length]; for (int i = 0; i < names.length; i++) { @@ -31,6 +32,7 @@ public String[] getAttributeNames() { return names; } + // crea la tabla public void createTable() { String[] attributeStrings = new String[attributes.length]; for (int i = 0; i < attributes.length; i++) { @@ -39,10 +41,12 @@ public void createTable() { Connector.createTable(DBNAME, name, String.join(", ", attributeStrings)); } + // inserta un registro con los valores `values` en las respectivas columnas `columns` public void insert(String[] columns, String[] values) { Connector.insert(DBNAME, name, String.join(", ", columns), "'"+String.join("', '", values)+"'"); } + // retorna una matriz con todos los elementos public List select() { ResultSet resultSet = Connector.select(DBNAME,name); List rows = new ArrayList<>(); @@ -60,5 +64,28 @@ public List select() { } return rows; } + + // elimina el registro cuyos valores (de todas las columnas) son `values` + public void delete(String[] values) { + Connector.delete(DBNAME, name, + "("+String.join(", ", getAttributeNames())+")", + "('"+String.join("', '", values)+"')" + ); + } + + // modifica el registro cuyos valores (de todas las columnas) son `current_values` + // asigna valores `new_values` a las respectivas columnas `new_values` + public void update(String[] current_values, String[] columns_to_update, String[] new_values) { + int n = columns_to_update.length; + String[] changes = new String[n]; + for (int i = 0; i < n; i++) { + changes[i] = columns_to_update[i] + " = '" + new_values[i] + "'"; + } + Connector.update(DBNAME, name, + "("+String.join(", ", getAttributeNames())+")", + "('"+String.join("', '", current_values)+"')", + String.join(", ", changes) + ); + } } diff --git a/Ejercicio1/src/main/java/views/Cliente_InsertView.java b/Ejercicio1/src/main/java/views/EditCliente_View.java similarity index 80% rename from Ejercicio1/src/main/java/views/Cliente_InsertView.java rename to Ejercicio1/src/main/java/views/EditCliente_View.java index 97fdf6a..9aa5af1 100644 --- a/Ejercicio1/src/main/java/views/Cliente_InsertView.java +++ b/Ejercicio1/src/main/java/views/EditCliente_View.java @@ -3,7 +3,6 @@ */ package views; -import java.sql.Date; import java.time.LocalDate; import java.time.format.DateTimeFormatter; @@ -12,10 +11,9 @@ /** * @author Javier - * @param - * + * insert or update */ -public class Cliente_InsertView extends JFrame { +public class EditCliente_View extends JFrame { private JPanel contentPane; public JTextField nombre; @@ -23,10 +21,10 @@ public class Cliente_InsertView extends JFrame { public JTextField direccion; public JTextField dni; public JTextField fecha; - public JButton crear; - public Date date; + public JButton button; + public JLabel labelTitle; - public Cliente_InsertView() { + public EditCliente_View() { initComponents(); } @@ -84,21 +82,13 @@ private void initComponents() { fecha.setBounds(107, 217, 201, 20); contentPane.add(fecha); - crear = new JButton("Crear"); - crear.setBounds(219, 307, 89, 23); - contentPane.add(crear); - - JLabel lblNewLabel = new JLabel("NUEVO CLIENTE"); - lblNewLabel.setBounds(124, 22, 138, 20); - contentPane.add(lblNewLabel); - - - - - - - + button = new JButton(); + button.setBounds(219, 250, 89, 23); + contentPane.add(button); + labelTitle = new JLabel(); + labelTitle.setBounds(124, 22, 138, 20); + contentPane.add(labelTitle); } diff --git a/Ejercicio1/src/main/java/views/Cliente_Index.java b/Ejercicio1/src/main/java/views/IndexView.java similarity index 92% rename from Ejercicio1/src/main/java/views/Cliente_Index.java rename to Ejercicio1/src/main/java/views/IndexView.java index 3f9f04a..0629619 100644 --- a/Ejercicio1/src/main/java/views/Cliente_Index.java +++ b/Ejercicio1/src/main/java/views/IndexView.java @@ -4,13 +4,12 @@ import javax.swing.JFrame; import javax.swing.JPanel; -import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import java.awt.Font; import javax.swing.SwingConstants; import javax.swing.JButton; -public class Cliente_Index extends JFrame { +public class IndexView extends JFrame { public JPanel contentPane; public JButton nuevoCliente; @@ -25,7 +24,7 @@ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { - Cliente_Index frame = new Cliente_Index(); + IndexView frame = new IndexView(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); @@ -38,7 +37,7 @@ public void run() { * Create the frame. */ - public Cliente_Index() { + public IndexView() { initComponents(); } diff --git a/Ejercicio1/src/main/java/views/Cliente_ListView.java b/Ejercicio1/src/main/java/views/ListView.java similarity index 52% rename from Ejercicio1/src/main/java/views/Cliente_ListView.java rename to Ejercicio1/src/main/java/views/ListView.java index 8feb237..8169fc3 100644 --- a/Ejercicio1/src/main/java/views/Cliente_ListView.java +++ b/Ejercicio1/src/main/java/views/ListView.java @@ -9,13 +9,15 @@ * @author Javier * */ -public class Cliente_ListView extends JFrame{ +public class ListView extends JFrame{ private JPanel contentPane; public JTable table; - public JButton add; + public JButton insert; + public JButton update; + public JButton delete; - public Cliente_ListView() { + public ListView() { initComponents(); } @@ -32,8 +34,16 @@ private void initComponents() { clientes.setBounds(188, 20, 49, 14); contentPane.add(clientes); - add = new JButton("Añadir"); - add.setBounds(319, 227, 89, 23); - contentPane.add(add); + insert = new JButton("Añadir"); + insert.setBounds(54, 227, 89, 23); + contentPane.add(insert); + + update = new JButton("Modificar"); + update.setBounds(165, 227, 89, 23); + contentPane.add(update); + + delete = new JButton("Eliminar"); + delete.setBounds(283, 227, 89, 23); + contentPane.add(delete); } } From 2fe31ee93e42f4b55bf17ab744ab950e0db1a4f9 Mon Sep 17 00:00:00 2001 From: Joan Date: Thu, 13 Apr 2023 19:00:50 +0200 Subject: [PATCH 09/10] =?UTF-8?q?peque=C3=B1os=20cambios=20ejercicio1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/main/java/controller/EditCliente_Controller.java | 5 ++--- Ejercicio1/src/main/java/models/DataBase.java | 2 +- Ejercicio1/src/main/java/models/Table.java | 4 +--- Ejercicio1/src/main/java/views/EditCliente_View.java | 8 ++++---- 4 files changed, 8 insertions(+), 11 deletions(-) diff --git a/Ejercicio1/src/main/java/controller/EditCliente_Controller.java b/Ejercicio1/src/main/java/controller/EditCliente_Controller.java index 51a68c7..951e78e 100644 --- a/Ejercicio1/src/main/java/controller/EditCliente_Controller.java +++ b/Ejercicio1/src/main/java/controller/EditCliente_Controller.java @@ -9,7 +9,6 @@ import javax.swing.*; -import javafx.scene.chart.PieChart.Data; import models.*; import views.*; @@ -30,7 +29,7 @@ public EditCliente_Controller(ListController listController) { this.listController = listController; initVista(); view.setTitle("Nuevo cliente"); - view.labelTitle.setText("NUEVO CLIENTE"); + view.tituloVentana.setText("NUEVO CLIENTE"); view.button.setText("Añadir"); } @@ -40,7 +39,7 @@ public EditCliente_Controller(ListController listController, String[] elementToU this.elementToUpdate = elementToUpdate; initVista(); view.setTitle("Modificar cliente"); - view.labelTitle.setText("MODIFICAR CLIENTE"); + view.tituloVentana.setText("MODIFICAR CLIENTE"); view.button.setText("Modificar"); view.nombre.setText(elementToUpdate[1]); diff --git a/Ejercicio1/src/main/java/models/DataBase.java b/Ejercicio1/src/main/java/models/DataBase.java index 4752899..591a31f 100644 --- a/Ejercicio1/src/main/java/models/DataBase.java +++ b/Ejercicio1/src/main/java/models/DataBase.java @@ -17,7 +17,7 @@ public static void init() { new Attribute("DNI", "VARCHAR(250)", "DEFAULT NULL"), new Attribute("Fecha", "DATE", "DEFAULT NULL"), }; - cliente = new Table("clientes", attributes, new int[]{0}, DBNAME); + cliente = new Table("clientes", attributes, DBNAME); Connector.openConnection(); Connector.createDB(DBNAME); diff --git a/Ejercicio1/src/main/java/models/Table.java b/Ejercicio1/src/main/java/models/Table.java index 5c5d16a..831b11a 100644 --- a/Ejercicio1/src/main/java/models/Table.java +++ b/Ejercicio1/src/main/java/models/Table.java @@ -13,13 +13,11 @@ public class Table { public String name; public Attribute[] attributes; - public int[] primary_key; //indexs de attributes que son la primary key public final String DBNAME; - public Table(String name, Attribute[] attributes, int[] primary_key, String dbname) { + public Table(String name, Attribute[] attributes, String dbname) { this.name = name; this.attributes = attributes; - this.primary_key = primary_key; this.DBNAME = dbname; } diff --git a/Ejercicio1/src/main/java/views/EditCliente_View.java b/Ejercicio1/src/main/java/views/EditCliente_View.java index 9aa5af1..fea96ab 100644 --- a/Ejercicio1/src/main/java/views/EditCliente_View.java +++ b/Ejercicio1/src/main/java/views/EditCliente_View.java @@ -22,7 +22,7 @@ public class EditCliente_View extends JFrame { public JTextField dni; public JTextField fecha; public JButton button; - public JLabel labelTitle; + public JLabel tituloVentana; public EditCliente_View() { initComponents(); @@ -86,9 +86,9 @@ private void initComponents() { button.setBounds(219, 250, 89, 23); contentPane.add(button); - labelTitle = new JLabel(); - labelTitle.setBounds(124, 22, 138, 20); - contentPane.add(labelTitle); + tituloVentana = new JLabel(); + tituloVentana.setBounds(124, 22, 138, 20); + contentPane.add(tituloVentana); } From 3c8198bc16538ade540d6f5d59285e3643fa8bf4 Mon Sep 17 00:00:00 2001 From: Joan Date: Thu, 13 Apr 2023 21:41:24 +0200 Subject: [PATCH 10/10] Ejercicio 2 acabado --- .gitignore | 2 +- Ejercicio2/.classpath | 44 ++++++ Ejercicio2/.gitignore | 1 + Ejercicio2/.project | 34 ++++ .../org.eclipse.core.resources.prefs | 4 + .../.settings/org.eclipse.jdt.apt.core.prefs | 2 + .../.settings/org.eclipse.jdt.core.prefs | 111 +++++++++++++ .../.settings/org.eclipse.m2e.core.prefs | 4 + Ejercicio2/README.md | 1 + Ejercicio2/pom.xml | 32 ++++ Ejercicio2/src/main/java/app1Main/App.java | 29 ++++ .../controller/EditClientes_Controller.java | 99 ++++++++++++ .../controller/EditVideos_Controller.java | 87 ++++++++++ .../main/java/controller/IndexController.java | 42 +++++ .../main/java/controller/ListController.java | 95 +++++++++++ .../controller/ListSelect_Controller.java | 42 +++++ .../src/main/java/models/Attribute.java | 31 ++++ Ejercicio2/src/main/java/models/Cliente.java | 148 ++++++++++++++++++ .../src/main/java/models/Connector.java | 144 +++++++++++++++++ Ejercicio2/src/main/java/models/DataBase.java | 41 +++++ Ejercicio2/src/main/java/models/Table.java | 89 +++++++++++ .../main/java/views/EditClientes_View.java | 95 +++++++++++ .../src/main/java/views/EditVideos_View.java | 73 +++++++++ Ejercicio2/src/main/java/views/IndexView.java | 51 ++++++ .../src/main/java/views/ListSelect_View.java | 17 ++ Ejercicio2/src/main/java/views/ListView.java | 54 +++++++ .../src/test/java/app1Main/AppTest.java | 38 +++++ 27 files changed, 1409 insertions(+), 1 deletion(-) create mode 100644 Ejercicio2/.classpath create mode 100644 Ejercicio2/.gitignore create mode 100644 Ejercicio2/.project create mode 100644 Ejercicio2/.settings/org.eclipse.core.resources.prefs create mode 100644 Ejercicio2/.settings/org.eclipse.jdt.apt.core.prefs create mode 100644 Ejercicio2/.settings/org.eclipse.jdt.core.prefs create mode 100644 Ejercicio2/.settings/org.eclipse.m2e.core.prefs create mode 100644 Ejercicio2/README.md create mode 100644 Ejercicio2/pom.xml create mode 100644 Ejercicio2/src/main/java/app1Main/App.java create mode 100644 Ejercicio2/src/main/java/controller/EditClientes_Controller.java create mode 100644 Ejercicio2/src/main/java/controller/EditVideos_Controller.java create mode 100644 Ejercicio2/src/main/java/controller/IndexController.java create mode 100644 Ejercicio2/src/main/java/controller/ListController.java create mode 100644 Ejercicio2/src/main/java/controller/ListSelect_Controller.java create mode 100644 Ejercicio2/src/main/java/models/Attribute.java create mode 100644 Ejercicio2/src/main/java/models/Cliente.java create mode 100644 Ejercicio2/src/main/java/models/Connector.java create mode 100644 Ejercicio2/src/main/java/models/DataBase.java create mode 100644 Ejercicio2/src/main/java/models/Table.java create mode 100644 Ejercicio2/src/main/java/views/EditClientes_View.java create mode 100644 Ejercicio2/src/main/java/views/EditVideos_View.java create mode 100644 Ejercicio2/src/main/java/views/IndexView.java create mode 100644 Ejercicio2/src/main/java/views/ListSelect_View.java create mode 100644 Ejercicio2/src/main/java/views/ListView.java create mode 100644 Ejercicio2/src/test/java/app1Main/AppTest.java diff --git a/.gitignore b/.gitignore index fbd9690..b40b47d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -Ejercicio1/src/main/java/models/Credenciales.java +*/src/main/java/models/Credenciales.java diff --git a/Ejercicio2/.classpath b/Ejercicio2/.classpath new file mode 100644 index 0000000..f0257c5 --- /dev/null +++ b/Ejercicio2/.classpath @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Ejercicio2/.gitignore b/Ejercicio2/.gitignore new file mode 100644 index 0000000..b83d222 --- /dev/null +++ b/Ejercicio2/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/Ejercicio2/.project b/Ejercicio2/.project new file mode 100644 index 0000000..5e526a0 --- /dev/null +++ b/Ejercicio2/.project @@ -0,0 +1,34 @@ + + + ta22 + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.m2e.core.maven2Builder + + + + + + org.eclipse.jdt.core.javanature + org.eclipse.m2e.core.maven2Nature + + + + 1681308613605 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/Ejercicio2/.settings/org.eclipse.core.resources.prefs b/Ejercicio2/.settings/org.eclipse.core.resources.prefs new file mode 100644 index 0000000..f9fe345 --- /dev/null +++ b/Ejercicio2/.settings/org.eclipse.core.resources.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +encoding//src/main/java=UTF-8 +encoding//src/test/java=UTF-8 +encoding/=UTF-8 diff --git a/Ejercicio2/.settings/org.eclipse.jdt.apt.core.prefs b/Ejercicio2/.settings/org.eclipse.jdt.apt.core.prefs new file mode 100644 index 0000000..d4313d4 --- /dev/null +++ b/Ejercicio2/.settings/org.eclipse.jdt.apt.core.prefs @@ -0,0 +1,2 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.apt.aptEnabled=false diff --git a/Ejercicio2/.settings/org.eclipse.jdt.core.prefs b/Ejercicio2/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000..70d61cf --- /dev/null +++ b/Ejercicio2/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,111 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.builder.annotationPath.allLocations=disabled +org.eclipse.jdt.core.compiler.annotation.inheritNullAnnotations=disabled +org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore +org.eclipse.jdt.core.compiler.annotation.nonnull=org.eclipse.jdt.annotation.NonNull +org.eclipse.jdt.core.compiler.annotation.nonnull.secondary= +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=org.eclipse.jdt.annotation.NonNullByDefault +org.eclipse.jdt.core.compiler.annotation.nonnullbydefault.secondary= +org.eclipse.jdt.core.compiler.annotation.nullable=org.eclipse.jdt.annotation.Nullable +org.eclipse.jdt.core.compiler.annotation.nullable.secondary= +org.eclipse.jdt.core.compiler.annotation.nullanalysis=disabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8 +org.eclipse.jdt.core.compiler.compliance=1.8 +org.eclipse.jdt.core.compiler.problem.APILeak=warning +org.eclipse.jdt.core.compiler.problem.annotatedTypeArgumentToUnannotated=info +org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning +org.eclipse.jdt.core.compiler.problem.autoboxing=ignore +org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning +org.eclipse.jdt.core.compiler.problem.deadCode=warning +org.eclipse.jdt.core.compiler.problem.deprecation=warning +org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled +org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled +org.eclipse.jdt.core.compiler.problem.discouragedReference=warning +org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore +org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled +org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore +org.eclipse.jdt.core.compiler.problem.fallthroughCase=ignore +org.eclipse.jdt.core.compiler.problem.fatalOptionalError=disabled +org.eclipse.jdt.core.compiler.problem.fieldHiding=ignore +org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning +org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning +org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning +org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning +org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=disabled +org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning +org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning +org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore +org.eclipse.jdt.core.compiler.problem.localVariableHiding=ignore +org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning +org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore +org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled +org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=ignore +org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled +org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore +org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore +org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning +org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning +org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore +org.eclipse.jdt.core.compiler.problem.nonnullParameterAnnotationDropped=warning +org.eclipse.jdt.core.compiler.problem.nonnullTypeVariableFromLegacyInvocation=warning +org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=error +org.eclipse.jdt.core.compiler.problem.nullReference=warning +org.eclipse.jdt.core.compiler.problem.nullSpecViolation=error +org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=warning +org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning +org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore +org.eclipse.jdt.core.compiler.problem.pessimisticNullAnalysisForFreeTypeVariables=warning +org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=ignore +org.eclipse.jdt.core.compiler.problem.potentialNullReference=ignore +org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=ignore +org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning +org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning +org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore +org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore +org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore +org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore +org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled +org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning +org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=disabled +org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled +org.eclipse.jdt.core.compiler.problem.suppressWarningsNotFullyAnalysed=info +org.eclipse.jdt.core.compiler.problem.syntacticNullAnalysisForFields=disabled +org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore +org.eclipse.jdt.core.compiler.problem.terminalDeprecation=warning +org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning +org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=enabled +org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning +org.eclipse.jdt.core.compiler.problem.unclosedCloseable=warning +org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore +org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning +org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentType=warning +org.eclipse.jdt.core.compiler.problem.unlikelyCollectionMethodArgumentTypeStrict=disabled +org.eclipse.jdt.core.compiler.problem.unlikelyEqualsArgumentType=info +org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore +org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=ignore +org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore +org.eclipse.jdt.core.compiler.problem.unstableAutoModuleName=warning +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=ignore +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled +org.eclipse.jdt.core.compiler.problem.unusedExceptionParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedImport=warning +org.eclipse.jdt.core.compiler.problem.unusedLabel=warning +org.eclipse.jdt.core.compiler.problem.unusedLocal=warning +org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled +org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled +org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning +org.eclipse.jdt.core.compiler.problem.unusedTypeParameter=ignore +org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning +org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning +org.eclipse.jdt.core.compiler.processAnnotations=disabled +org.eclipse.jdt.core.compiler.release=disabled +org.eclipse.jdt.core.compiler.source=1.8 diff --git a/Ejercicio2/.settings/org.eclipse.m2e.core.prefs b/Ejercicio2/.settings/org.eclipse.m2e.core.prefs new file mode 100644 index 0000000..f897a7f --- /dev/null +++ b/Ejercicio2/.settings/org.eclipse.m2e.core.prefs @@ -0,0 +1,4 @@ +activeProfiles= +eclipse.preferences.version=1 +resolveWorkspaceProjects=true +version=1 diff --git a/Ejercicio2/README.md b/Ejercicio2/README.md new file mode 100644 index 0000000..9cd3dc2 --- /dev/null +++ b/Ejercicio2/README.md @@ -0,0 +1 @@ +# UD22 \ No newline at end of file diff --git a/Ejercicio2/pom.xml b/Ejercicio2/pom.xml new file mode 100644 index 0000000..66c4e42 --- /dev/null +++ b/Ejercicio2/pom.xml @@ -0,0 +1,32 @@ + + 4.0.0 + + 22 + ta22 + 0.0.1-SNAPSHOT + jar + + ta22 + http://maven.apache.org + + + UTF-8 + 1.8 + 1.8 + + + + + junit + junit + 3.8.1 + test + + + mysql + mysql-connector-java + 8.0.32 + + + diff --git a/Ejercicio2/src/main/java/app1Main/App.java b/Ejercicio2/src/main/java/app1Main/App.java new file mode 100644 index 0000000..0848eb8 --- /dev/null +++ b/Ejercicio2/src/main/java/app1Main/App.java @@ -0,0 +1,29 @@ +package app1Main; + +import javax.swing.*; +import controller.*; +import models.DataBase; + +/** + * @author Javier + * + */ +public class App { + public static void main( String[] args ) { + + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } + catch (UnsupportedLookAndFeelException e) { + } + catch (ClassNotFoundException e) { + } + catch (InstantiationException e) { + } + catch (IllegalAccessException e) { + } + + DataBase.init(); + new IndexController(); + } +} diff --git a/Ejercicio2/src/main/java/controller/EditClientes_Controller.java b/Ejercicio2/src/main/java/controller/EditClientes_Controller.java new file mode 100644 index 0000000..9fc95f5 --- /dev/null +++ b/Ejercicio2/src/main/java/controller/EditClientes_Controller.java @@ -0,0 +1,99 @@ +/** + * + */ +package controller; + +import java.awt.event.*; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +import javax.swing.*; + +import models.*; +import views.*; + +/** + * @author Joan + * Esta clase añade (insert) o modifica (update) un elemento de la tabla cliente + * Si elementToUpdate==null, inserta un nuevo elemento + * Si no, modifica el elemento cuyos campos son elementToUpdate + */ +public class EditClientes_Controller implements ActionListener { + + private EditClientes_View view; + private ListController listController; + private String[] elementToUpdate = null; + private Table table = DataBase.clientes; + + // insert cliente + public EditClientes_Controller(ListController listController) { + this.listController = listController; + initVista(); + view.setTitle("Nuevo cliente"); + view.tituloVentana.setText("NUEVO CLIENTE"); + view.button.setText("Añadir"); + } + + // update cliente + public EditClientes_Controller(ListController listController, String[] elementToUpdate) { + this.listController = listController; + this.elementToUpdate = elementToUpdate; + initVista(); + view.setTitle("Modificar cliente"); + view.tituloVentana.setText("MODIFICAR CLIENTE"); + view.button.setText("Modificar"); + + view.nombre.setText(elementToUpdate[1]); + view.apellidos.setText(elementToUpdate[2]); + view.direccion.setText(elementToUpdate[3]); + view.dni.setText(elementToUpdate[4]); + view.fecha.setText(elementToUpdate[5]); + } + + public void initVista() { + view = new EditClientes_View(); + view.button.addActionListener(this); + view.setBounds(300, 300, 354, 351); + view.setLocationRelativeTo(null); + view.setVisible(true); + } + + @Override + public void actionPerformed(ActionEvent e) { + String nombre = view.nombre.getText(); + String apellidos = view.apellidos.getText(); + String direccion = view.direccion.getText(); + int dni = 0; + java.sql.Date fecha = null; + + try { + dni = Integer.parseInt(view.dni.getText()); + } catch (Exception ex) { + JOptionPane.showMessageDialog(view, "El DNI debe ser un número entero"); + return; + } + try { + String fechaTexto = view.fecha.getText(); // Obtener el texto del campo de fecha + DateTimeFormatter formatoFecha = DateTimeFormatter.ofPattern("yyyy-MM-dd");//establecer el formato + LocalDate fechaLocal = LocalDate.parse(fechaTexto, formatoFecha); // Analizar el texto de la fecha y crear un objeto LocalDate a partir de ella + fecha = java.sql.Date.valueOf(fechaLocal); // Convertir el objeto LocalDate a un objeto java.sql.Date + } catch (Exception ex) { + JOptionPane.showMessageDialog(view, "El formato de la fecha es incorrecto (formato deseado: aaaa-mm-dd)"); + return; + } + + String[] columns = {"nombre", "apellido", "direccion", "dni", "fecha"}; + String[] values = {nombre,apellidos,direccion,Integer.toString(dni),fecha.toString()}; + if (elementToUpdate == null) { + table.insert(columns, values); + } + else { + table.update(elementToUpdate, columns, values); + } + listController.refreshList(); + view.dispose(); + + } + + +} diff --git a/Ejercicio2/src/main/java/controller/EditVideos_Controller.java b/Ejercicio2/src/main/java/controller/EditVideos_Controller.java new file mode 100644 index 0000000..8db3e37 --- /dev/null +++ b/Ejercicio2/src/main/java/controller/EditVideos_Controller.java @@ -0,0 +1,87 @@ +/** + * + */ +package controller; + +import java.awt.event.*; + +import javax.swing.JOptionPane; +import javax.swing.text.View; + +import models.*; +import views.*; + +/** + * @author Joan + * Esta clase añade (INSERT) o modifica (UPDATE) un elemento de la tabla cliente + * Si elementToUpdate==null, inserta un nuevo elemento + * Si no, modifica el elemento cuyos campos son elementToUpdate + */ +public class EditVideos_Controller implements ActionListener { + + private EditVideos_View view; + private ListController listController; + private String[] elementToUpdate = null; + private Table table = DataBase.videos; + + // insert cliente + public EditVideos_Controller(ListController listController) { + this.listController = listController; + initVista(); + view.setTitle("Nuevo vídeo"); + view.tituloVentana.setText("NUEVO VÍDEO"); + view.button.setText("Añadir"); + } + + // update cliente + public EditVideos_Controller(ListController listController, String[] elementToUpdate) { + this.listController = listController; + this.elementToUpdate = elementToUpdate; + initVista(); + view.setTitle("Modificar vídeo"); + view.tituloVentana.setText("MODIFICAR VÍDEO"); + view.button.setText("Modificar"); + + view.titulo.setText(elementToUpdate[1]); + view.director.setText(elementToUpdate[2]); + view.cli_id.setText(elementToUpdate[3]); + } + + public void initVista() { + view = new EditVideos_View(); + view.button.addActionListener(this); + view.seleccionarCliente.addActionListener(this); + view.setBounds(300, 300, 354, 351); + view.setLocationRelativeTo(null); + view.setVisible(true); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == view.button) { + if (view.cli_id.getText() == "") { + JOptionPane.showMessageDialog(view, "Seleccione un cliente"); + } + + String titulo = view.titulo.getText(); + String director = view.director.getText(); + String cli_id = view.cli_id.getText(); + + String[] columns = {"titulo", "director", "cli_id"}; + String[] values = {titulo,director,cli_id}; + if (elementToUpdate == null) { + table.insert(columns, values); + } + else { + table.update(elementToUpdate, columns, values); + } + listController.refreshList(); + view.dispose(); + } + else { + new ListSelect_Controller(DataBase.clientes, view.cli_id); + } + } + + +} diff --git a/Ejercicio2/src/main/java/controller/IndexController.java b/Ejercicio2/src/main/java/controller/IndexController.java new file mode 100644 index 0000000..7435e0e --- /dev/null +++ b/Ejercicio2/src/main/java/controller/IndexController.java @@ -0,0 +1,42 @@ +package controller; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +import javax.swing.JFrame; +import javax.swing.border.EmptyBorder; + +import models.DataBase; +import views.IndexView; + +public class IndexController implements ActionListener{ + + private IndexView view; + + + + public IndexController() { + view = new IndexView(); + view.clientes.addActionListener(this); + view.videos.addActionListener(this); + initVista(); + } + + public void initVista() { + view.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + view.setBounds(100, 100, 534, 473); + + view.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); + view.setVisible(true); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == view.clientes) { + new ListController(DataBase.clientes); + } else if (e.getSource() == view.videos) { + new ListController(DataBase.videos); + } + } + +} diff --git a/Ejercicio2/src/main/java/controller/ListController.java b/Ejercicio2/src/main/java/controller/ListController.java new file mode 100644 index 0000000..1c802a3 --- /dev/null +++ b/Ejercicio2/src/main/java/controller/ListController.java @@ -0,0 +1,95 @@ +package controller; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.util.List; +import views.ListView; +import javax.swing.JOptionPane; +import javax.swing.table.DefaultTableModel; + +import models.DataBase; +import models.Table; + + + +public class ListController implements ActionListener { + + protected ListView view; + protected Table table; + + public ListController() {} + + public ListController(Table table) { + this.table = table; + view = new ListView(); + view.insert.addActionListener(this); + view.delete.addActionListener(this); + view.update.addActionListener(this); + initVista(); + refreshList(); + } + + public void initVista() { + view.setTitle("Lista de "+table.name); + view.setBounds(300, 300, 450, 351); + view.setLocationRelativeTo(null); + view.setVisible(true); + view.window_title.setText(table.name); + } + + public void refreshList() { + view.table.setModel(list()); + } + + private DefaultTableModel list() { + List rows = table.select(); + DefaultTableModel model = new DefaultTableModel(table.getAttributeNames(), 0); + for (String[] row : rows) { + model.addRow(row); + } + return model; + } + + private String[] getRowValues() { + int row = view.table.getSelectedRow(); + if (row == -1) { + JOptionPane.showMessageDialog(view, "Seleccione una fila"); + return null; + } + int n = view.table.getColumnCount(); + String[] values = new String[n]; + for (int i = 0; i < n; i++) { + values[i] = view.table.getValueAt(row, i).toString(); + } + return values; + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == view.insert) { + if (table == DataBase.clientes) + new EditClientes_Controller(this); + else if (table == DataBase.videos) + new EditVideos_Controller(this); + } + else if (e.getSource() == view.update) { + String[] row_values = getRowValues(); + if (row_values != null) { + if (table == DataBase.clientes) + new EditClientes_Controller(this, row_values); + else if (table == DataBase.videos) + new EditVideos_Controller(this, row_values); + } + } + else if (e.getSource() == view.delete) { + String[] row_values = getRowValues(); + if (row_values != null) { + if (0 == JOptionPane.showConfirmDialog(view, "¿Está seguro de que quiere eliminar este cliente?")) { + table.delete(row_values); + refreshList(); + } + } + } + + } +} diff --git a/Ejercicio2/src/main/java/controller/ListSelect_Controller.java b/Ejercicio2/src/main/java/controller/ListSelect_Controller.java new file mode 100644 index 0000000..b6ede77 --- /dev/null +++ b/Ejercicio2/src/main/java/controller/ListSelect_Controller.java @@ -0,0 +1,42 @@ +package controller; + +import views.ListSelect_View; + +import java.awt.event.ActionEvent; + +import javax.swing.JLabel; +import javax.swing.JOptionPane; + +import models.Table; + +/** + * @author Joan + * Esta clase se usa cuando hay que definir una Foregin Key + * Se abre una vista que muestra todos los registros de la tabla + * a la que apunta la Foregin Key y el usuario selecciona uno. + */ +public class ListSelect_Controller extends ListController { + + private JLabel result; // label donde irá el resultado de la selección + + public ListSelect_Controller(Table table, JLabel result) { + this.table = table; + this.result = result; + view = new ListSelect_View(); + view.select.addActionListener(this); + initVista(); + refreshList(); + } + + @Override + public void actionPerformed(ActionEvent e) { + int row = view.table.getSelectedRow(); + if (row == -1) { + JOptionPane.showMessageDialog(view, "Seleccione una fila"); + return; + } + String value = view.table.getValueAt(row, 0).toString(); //asumimos que la PK es la primera columna + result.setText(value); + view.dispose(); + } +} diff --git a/Ejercicio2/src/main/java/models/Attribute.java b/Ejercicio2/src/main/java/models/Attribute.java new file mode 100644 index 0000000..ed82e06 --- /dev/null +++ b/Ejercicio2/src/main/java/models/Attribute.java @@ -0,0 +1,31 @@ +package models; + +/** + * @author Joan + * esta clase representa el atributo de una tabla de una BD + */ +public class Attribute { + public String name; + public String type; + public String others = ""; + + // example: JEFE CHARVAR(30) NOT NULL REFERENCES EMPLEADO + // name="JEFE", type="CHARVAR", type_cardinality="(30)", + // others=["NOT", "NULL", "REFERENCES", "EMPLEADO"] + + + Attribute(String name, String type) { + this.name = name; + this.type = type; + } + Attribute(String name, String type, String others) { + this.name = name; + this.type = type; + this.others = others; + } + + @Override + public String toString() { + return name + " " + type + " " + others; + } +} diff --git a/Ejercicio2/src/main/java/models/Cliente.java b/Ejercicio2/src/main/java/models/Cliente.java new file mode 100644 index 0000000..be06d27 --- /dev/null +++ b/Ejercicio2/src/main/java/models/Cliente.java @@ -0,0 +1,148 @@ +/** + * + */ +package models; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.*; + +/** + * @author Javier + * + */ +public class Cliente { + + // Atributes + private int id; + private String nombre; + private String apellido; + private String direccion; + private int dni; + private Date fecha; + + private static final String DBNAME = "servicios"; + private static final String TBNAME = "clientes"; + + // Constructor + + public Cliente() { + } + + public Cliente(int id, String nombre, String apellido, String direccion, int dni, Date fecha) { + + this.id = id; + this.nombre = nombre; + this.apellido = apellido; + this.direccion = direccion; + this.dni = dni; + this.fecha = fecha; + + createDatabase(); + createTable(); + } + + // Methods + /** + * This method create de database if exists. + */ + public void createDatabase() { + Connector.createDB(DBNAME); + } + + /** + * This method create table "clientes". + */ + public void createTable() { + Connector.createTable(DBNAME, TBNAME, + "id INT(11) NOT NULL AUTO_INCREMENT PRIMARY KEY," + + "nombre VARCHAR(250) NOT NULL," + + "apellido VARCHAR(250) NOT NULL," + + "direccion VARCHAR(250) NOT NULL," + + "dni INT(11) DEFAULT NULL," + + "fecha DATE DEFAULT NULL"); + } + + /** + * This method insert data into database. + */ + public void insert() { + Connector.insert(DBNAME, TBNAME, + "nombre, apellido, direccion, dni, fecha", + "'" + this.nombre + "', '" + this.apellido + "', '" + this.direccion + "', " + this.dni + ", '" + this.fecha + "'"); + } + + /* + * This method select data. + */ + public List select() { + ResultSet resultSet = Connector.select(DBNAME,TBNAME); + List clientes = new ArrayList<>(); + try { + while (resultSet.next()) { + Cliente c = new Cliente( + resultSet.getInt("id"), + resultSet.getString("nombre"), + resultSet.getString("apellido"), + resultSet.getString("direccion"), + resultSet.getInt("dni"), + resultSet.getDate("fecha")); + clientes.add(c); + } + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + System.out.println("Error en la conversión de resultados a objetos Cliente"); + } + return clientes; + } + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getNombre() { + return nombre; + } + + public void setNombre(String nombre) { + this.nombre = nombre; + } + + public String getApellido() { + return apellido; + } + + public void setApellido(String apellido) { + this.apellido = apellido; + } + + public String getDireccion() { + return direccion; + } + + public void setDireccion(String direccion) { + this.direccion = direccion; + } + + public int getDni() { + return dni; + } + + public void setDni(int dni) { + this.dni = dni; + } + + public Date getFecha() { + return fecha; + } + + public void setFecha(Date fecha) { + this.fecha = fecha; + } + + +} diff --git a/Ejercicio2/src/main/java/models/Connector.java b/Ejercicio2/src/main/java/models/Connector.java new file mode 100644 index 0000000..4430c8b --- /dev/null +++ b/Ejercicio2/src/main/java/models/Connector.java @@ -0,0 +1,144 @@ +package models; + +import java.sql.*; +import java.util.logging.*; +import javax.swing.JOptionPane; + + + +public class Connector { + + private static final String DRIVER = "com.mysql.cj.jdbc.Driver"; + private static final String URL = Credenciales.URL; + private static final String USER = Credenciales.USER; + private static final String PASSWORD = Credenciales.PASSWORD; + private static Connection conexion = null; + + public static void openConnection() { + try { + Class.forName(DRIVER); + conexion = DriverManager.getConnection(URL, USER, PASSWORD); + System.out.println("Server Connected"); + } catch(SQLException | ClassNotFoundException ex) { + System.out.print("No se ha podido conectar con mi base de datos"); + System.out.println(ex); + } + } + + public static void closeConnection() { + try { + conexion.close(); + JOptionPane.showMessageDialog(null, "Se ha finalizado la conexion con el servidor"); + } catch (SQLException ex) { + Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); + } + } + + // Create database + public static void createDB(String dbName) { + try { + String query = " CREATE DATABASE IF NOT EXISTS " + dbName + " ;"; + Statement st = conexion.createStatement(); + System.out.println(query); + st.executeUpdate(query); + System.out.println("\tSe ha creado la base de datos " + dbName + " correctamente"); + } catch (SQLException ex) { + Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); + } + } + + // Create table + public static void createTable(String nombreBBDD, String nombreTabla, String tablaColum) { + try { + String queryDb = "USE " + nombreBBDD + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "CREATE TABLE IF NOT EXISTS " + nombreTabla + " (" + tablaColum + ");"; + Statement st = conexion.createStatement(); + System.out.println(query); + st.executeUpdate(query); + + System.out.println("\tSe ha creado la tabla " + nombreTabla + " correctamente"); + } catch (SQLException ex) { + Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); + JOptionPane.showMessageDialog(null, "Error creando la tabla " + nombreTabla); + } + } + + // Insert row to table table + public static void insert(String dbName, String tableName, String columns, String values) { + try { + String queryDb = "USE " + dbName + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "INSERT INTO " + tableName + " (" + columns + ") VALUES (" + values + ");"; + Statement st = conexion.createStatement(); + System.out.println(query); + st.executeUpdate(query); + + System.out.println("\tDatos insertados correctamente en la tabla " + tableName); + } catch (SQLException ex) { + //Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex); + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error insertando datos en la tabla"); + } + } + + // Select all rows from table + public static ResultSet select(String db, String table_name) { + try { + String queryDb = "USE " + db + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "SELECT * FROM " + table_name; + Statement st = conexion.createStatement(); + System.out.println(query); + return st.executeQuery(query); + + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error en la adquisicion de datos"); + return null; + } + } + + // Delete + public static void delete(String db, String table_name, String column, String value) { + try { + String queryDb = "USE " + db + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "DELETE FROM " + table_name + " WHERE " + column + " = " + value; + Statement st = conexion.createStatement(); + System.out.println(query); + st.executeUpdate(query); + + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error borrando el registro especificado"); + } + } + + // Delete + public static void update(String db, String table_name, String column, String value, String changes) { + try { + String queryDb = "USE " + db + ";"; + Statement stdb = conexion.createStatement(); + stdb.executeUpdate(queryDb); + + String query = "UPDATE " + table_name + " SET " + changes + + " WHERE " + column + " = " + value + " "; + Statement st = conexion.createStatement(); + System.out.println(query); + st.executeUpdate(query); + + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + JOptionPane.showMessageDialog(null, "Error borrando el registro especificado"); + } + } +} \ No newline at end of file diff --git a/Ejercicio2/src/main/java/models/DataBase.java b/Ejercicio2/src/main/java/models/DataBase.java new file mode 100644 index 0000000..9ab26b3 --- /dev/null +++ b/Ejercicio2/src/main/java/models/DataBase.java @@ -0,0 +1,41 @@ +package models; + +/** + * @author Joan + * + */ +public class DataBase { + + // para ser consistente con ListSelect_Controller una tabla que es referenciada por otra + // debe tener una sola Primary Key, que tiene que ser el primer areibuto + + public static String DBNAME = "UD22_EJ2"; + public static Table clientes; + public static Table videos; + + public static void init() { + Attribute[] att_cliente = { + new Attribute("id", "INT(11)", "NOT NULL AUTO_INCREMENT PRIMARY KEY"), + new Attribute("nombre", "VARCHAR(250)", "NOT NULL"), + new Attribute("apellido", "VARCHAR(250)", "NOT NULL"), + new Attribute("direccion", "VARCHAR(250)", "NOT NULL"), + new Attribute("dni", "VARCHAR(250)", "DEFAULT NULL"), + new Attribute("fecha", "DATE", "DEFAULT NULL"), + }; + clientes = new Table("clientes", att_cliente, DBNAME); + Attribute[] att_video = { + new Attribute("id", "INT(11)", "NOT NULL AUTO_INCREMENT PRIMARY KEY"), + new Attribute("titulo", "VARCHAR(250)", "DEFAULT NULL"), + new Attribute("director", "VARCHAR(250)", "DEFAULT NULL"), + new Attribute("cli_id", "INT(11)", "DEFAULT NULL REFERENCES clientes(id)") + }; + videos = new Table("videos", att_video, DBNAME); + + Connector.openConnection(); + Connector.createDB(DBNAME); + clientes.createTable(); + videos.createTable(); + } + + +} diff --git a/Ejercicio2/src/main/java/models/Table.java b/Ejercicio2/src/main/java/models/Table.java new file mode 100644 index 0000000..831b11a --- /dev/null +++ b/Ejercicio2/src/main/java/models/Table.java @@ -0,0 +1,89 @@ +package models; + +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * @author Joan + * Esta clase es una forma genérica de representar tablas SQL + * usable para otros ejercicios similares + */ +public class Table { + public String name; + public Attribute[] attributes; + public final String DBNAME; + + public Table(String name, Attribute[] attributes, String dbname) { + this.name = name; + this.attributes = attributes; + this.DBNAME = dbname; + } + + // retorna un array con los nombres de los atributos + public String[] getAttributeNames() { + String[] names = new String[attributes.length]; + for (int i = 0; i < names.length; i++) { + names[i] = attributes[i].name; + } + return names; + } + + // crea la tabla + public void createTable() { + String[] attributeStrings = new String[attributes.length]; + for (int i = 0; i < attributes.length; i++) { + attributeStrings[i] = attributes[i].toString(); + } + Connector.createTable(DBNAME, name, String.join(", ", attributeStrings)); + } + + // inserta un registro con los valores `values` en las respectivas columnas `columns` + public void insert(String[] columns, String[] values) { + Connector.insert(DBNAME, name, String.join(", ", columns), "'"+String.join("', '", values)+"'"); + } + + // retorna una matriz con todos los elementos + public List select() { + ResultSet resultSet = Connector.select(DBNAME,name); + List rows = new ArrayList<>(); + try { + while (resultSet.next()) { + String[] row = new String[attributes.length]; + for (int i = 0; i < attributes.length; i++) { + row[i] = resultSet.getString(attributes[i].name); + } + rows.add(row); + } + } catch (SQLException ex) { + System.out.println(ex.getMessage()); + System.out.println("Error en la conversión de resultados a objetos Cliente"); + } + return rows; + } + + // elimina el registro cuyos valores (de todas las columnas) son `values` + public void delete(String[] values) { + Connector.delete(DBNAME, name, + "("+String.join(", ", getAttributeNames())+")", + "('"+String.join("', '", values)+"')" + ); + } + + // modifica el registro cuyos valores (de todas las columnas) son `current_values` + // asigna valores `new_values` a las respectivas columnas `new_values` + public void update(String[] current_values, String[] columns_to_update, String[] new_values) { + int n = columns_to_update.length; + String[] changes = new String[n]; + for (int i = 0; i < n; i++) { + changes[i] = columns_to_update[i] + " = '" + new_values[i] + "'"; + } + Connector.update(DBNAME, name, + "("+String.join(", ", getAttributeNames())+")", + "('"+String.join("', '", current_values)+"')", + String.join(", ", changes) + ); + } + +} diff --git a/Ejercicio2/src/main/java/views/EditClientes_View.java b/Ejercicio2/src/main/java/views/EditClientes_View.java new file mode 100644 index 0000000..38e1914 --- /dev/null +++ b/Ejercicio2/src/main/java/views/EditClientes_View.java @@ -0,0 +1,95 @@ +/** + * + */ +package views; + + +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + +import javax.swing.*; + +/** + * @author Javier + * insert or update + */ +public class EditClientes_View extends JFrame { + + private JPanel contentPane; + public JTextField nombre; + public JTextField apellidos; + public JTextField direccion; + public JTextField dni; + public JTextField fecha; + public JButton button; + public JLabel tituloVentana; + + public EditClientes_View() { + initComponents(); + } + + private void initComponents() { + + contentPane = new JPanel(); + setContentPane(contentPane); + contentPane.setLayout(null); + + JLabel lNombre = new JLabel("Nombre:"); + lNombre.setBounds(34, 56, 61, 14); + contentPane.add(lNombre); + + JLabel lApellidos = new JLabel("Apellidos:"); + lApellidos.setBounds(34, 100, 61, 14); + contentPane.add(lApellidos); + + JLabel lDireccion = new JLabel("Dirección:"); + lDireccion.setBounds(34, 142, 61, 14); + contentPane.add(lDireccion); + + JLabel lDni = new JLabel("DNI:"); + lDni.setBounds(34, 183, 46, 14); + contentPane.add(lDni); + + JLabel lFecha = new JLabel("Fecha:"); + lFecha.setBounds(34, 220, 46, 14); + contentPane.add(lFecha); + + nombre = new JTextField(); + nombre.setBounds(107, 53, 201, 20); + contentPane.add(nombre); + nombre.setColumns(10); + + apellidos = new JTextField(); + apellidos.setColumns(10); + apellidos.setBounds(107, 97, 201, 20); + contentPane.add(apellidos); + + direccion = new JTextField(); + direccion.setColumns(10); + direccion.setBounds(107, 139, 201, 20); + contentPane.add(direccion); + + dni = new JTextField(); + dni.setColumns(10); + dni.setBounds(107, 180, 201, 20); + contentPane.add(dni); + + fecha = new JTextField(); + //creamos una fecha actual por defecto + DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd"); + fecha.setText(LocalDate.now().format(dateFormat)); + fecha.setColumns(10); + fecha.setBounds(107, 217, 201, 20); + contentPane.add(fecha); + + button = new JButton(); + button.setBounds(219, 250, 89, 23); + contentPane.add(button); + + tituloVentana = new JLabel(); + tituloVentana.setBounds(124, 22, 138, 20); + contentPane.add(tituloVentana); + + + } +} \ No newline at end of file diff --git a/Ejercicio2/src/main/java/views/EditVideos_View.java b/Ejercicio2/src/main/java/views/EditVideos_View.java new file mode 100644 index 0000000..5d1e1a7 --- /dev/null +++ b/Ejercicio2/src/main/java/views/EditVideos_View.java @@ -0,0 +1,73 @@ +/** + * + */ +package views; + +import javax.swing.*; + +/** + * @author Javier + * insert or update + */ +public class EditVideos_View extends JFrame { + + private JPanel contentPane; + public JTextField titulo; + public JTextField director; + public JButton seleccionarCliente; + public JLabel cli_id; + public JButton button; + public JLabel tituloVentana; + + public EditVideos_View() { + initComponents(); + } + + private void initComponents() { + + contentPane = new JPanel(); + setContentPane(contentPane); + contentPane.setLayout(null); + + tituloVentana = new JLabel(); + tituloVentana.setBounds(124, 22, 138, 20); + contentPane.add(tituloVentana); + + button = new JButton(); + button.setBounds(219, 195, 89, 23); + contentPane.add(button); + + JLabel lTitulo = new JLabel("Título:"); + lTitulo.setBounds(34, 56, 61, 14); + contentPane.add(lTitulo); + + JLabel lDirector = new JLabel("Director:"); + lDirector.setBounds(34, 100, 61, 14); + contentPane.add(lDirector); + + JLabel lCliente = new JLabel("Cliente:"); + lCliente.setBounds(34, 142, 61, 14); + contentPane.add(lCliente); + + titulo = new JTextField(); + titulo.setBounds(107, 53, 201, 20); + contentPane.add(titulo); + titulo.setColumns(10); + + director = new JTextField(); + director.setColumns(10); + director.setBounds(107, 97, 201, 20); + contentPane.add(director); + + seleccionarCliente = new JButton("Seleccionar cliente"); + seleccionarCliente.setBounds(105, 138, 150, 23); + contentPane.add(seleccionarCliente); + + cli_id = new JLabel(""); + cli_id.setBounds(260, 142, 20, 14); + contentPane.add(cli_id); + + + + } +} \ No newline at end of file diff --git a/Ejercicio2/src/main/java/views/IndexView.java b/Ejercicio2/src/main/java/views/IndexView.java new file mode 100644 index 0000000..52d9d76 --- /dev/null +++ b/Ejercicio2/src/main/java/views/IndexView.java @@ -0,0 +1,51 @@ +package views; + +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JLabel; +import java.awt.Font; +import javax.swing.SwingConstants; +import javax.swing.JButton; + +public class IndexView extends JFrame { + + public JPanel contentPane; + public JButton clientes; + public JButton videos; + + /** + * Create the frame. + */ + + public IndexView() { + initComponents(); + } + + public void initComponents() { + + contentPane = new JPanel(); + setContentPane(contentPane); + contentPane.setLayout(null); + + JPanel panel = new JPanel(); + panel.setBounds(267, 14, 1, 1); + contentPane.add(panel); + panel.setLayout(null); + + JLabel lblBienvenido = new JLabel("Gestor de clientes y películas"); + lblBienvenido.setHorizontalAlignment(SwingConstants.CENTER); + lblBienvenido.setFont(new Font("Tahoma", Font.BOLD, 18)); + lblBienvenido.setBounds(86, 26, 329, 62); + contentPane.add(lblBienvenido); + + clientes = new JButton("Clientes"); + clientes.setFont(new Font("Tahoma", Font.PLAIN, 16)); + clientes.setBounds(180, 100, 144, 40); + contentPane.add(clientes); + + videos = new JButton("Vídeos"); + videos.setFont(new Font("Tahoma", Font.PLAIN, 16)); + videos.setBounds(180, 166, 144, 40); + contentPane.add(videos); + } +} diff --git a/Ejercicio2/src/main/java/views/ListSelect_View.java b/Ejercicio2/src/main/java/views/ListSelect_View.java new file mode 100644 index 0000000..da55727 --- /dev/null +++ b/Ejercicio2/src/main/java/views/ListSelect_View.java @@ -0,0 +1,17 @@ +package views; + +import javax.swing.*; + +/** + * @author Joan + * + */ +public class ListSelect_View extends ListView { + public ListSelect_View() { + initComponents(); + + select = new JButton("Aceptar"); + select.setBounds(165, 227, 89, 23); + contentPane.add(select); + } +} diff --git a/Ejercicio2/src/main/java/views/ListView.java b/Ejercicio2/src/main/java/views/ListView.java new file mode 100644 index 0000000..d3f3cde --- /dev/null +++ b/Ejercicio2/src/main/java/views/ListView.java @@ -0,0 +1,54 @@ +/** + * + */ +package views; + +import javax.swing.*; + +/** + * @author Javier + * + */ +public class ListView extends JFrame{ + + protected JPanel contentPane; + public JTable table; + public JButton insert; + public JButton update; + public JButton delete; + public JButton select; // solo se usa en la subclase ListSelect_View + public JLabel window_title; + + public ListView() { + initComponents(); + initButtons(); + } + + protected void initComponents() { + contentPane = new JPanel(); + setContentPane(contentPane); + contentPane.setLayout(null); + + table = new JTable(); + table.setBounds(20, 45, 388, 171); + contentPane.add(table); + + window_title = new JLabel(); + window_title.setBounds(188, 20, 49, 14); + contentPane.add(window_title); + } + + private void initButtons() { + insert = new JButton("Añadir"); + insert.setBounds(54, 227, 89, 23); + contentPane.add(insert); + + update = new JButton("Modificar"); + update.setBounds(165, 227, 89, 23); + contentPane.add(update); + + delete = new JButton("Eliminar"); + delete.setBounds(283, 227, 89, 23); + contentPane.add(delete); + } +} diff --git a/Ejercicio2/src/test/java/app1Main/AppTest.java b/Ejercicio2/src/test/java/app1Main/AppTest.java new file mode 100644 index 0000000..67ca083 --- /dev/null +++ b/Ejercicio2/src/test/java/app1Main/AppTest.java @@ -0,0 +1,38 @@ +package app1Main; + +import junit.framework.Test; +import junit.framework.TestCase; +import junit.framework.TestSuite; + +/** + * Unit test for simple App. + */ +public class AppTest + extends TestCase +{ + /** + * Create the test case + * + * @param testName name of the test case + */ + public AppTest( String testName ) + { + super( testName ); + } + + /** + * @return the suite of tests being tested + */ + public static Test suite() + { + return new TestSuite( AppTest.class ); + } + + /** + * Rigourous Test :-) + */ + public void testApp() + { + assertTrue( true ); + } +}