diff --git a/clientes.sqlite b/clientes.sqlite new file mode 100644 index 0000000..53c3637 Binary files /dev/null and b/clientes.sqlite differ diff --git a/mibd.db b/mibd.db index e69de29..669080f 100644 Binary files a/mibd.db and b/mibd.db differ diff --git a/src/main/java/iesthiar/EjemploSQLite.java b/src/main/java/iesthiar/EjemploSQLite.java index 377a6ff..f96930e 100644 --- a/src/main/java/iesthiar/EjemploSQLite.java +++ b/src/main/java/iesthiar/EjemploSQLite.java @@ -4,33 +4,60 @@ import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; +import java.sql.Statement; public class EjemploSQLite { public static void main(String[] args) { try (Connection c = DriverManager.getConnection("jdbc:sqlite:mibd.db"); - PreparedStatement pstm=c.prepareStatement("SELECT name FROM sqlite_master WHERE type='table' AND name='cliente';"); - ) { - System.out.println("Base de datos conectada"); - // Crear las tablas si es necesario - try (ResultSet rs=pstm.executeQuery()){ - if (rs.next()){ - System.out.println("Existe"); - } - else { + // Con esto comnprobamos si existen la tabla clientes + PreparedStatement pstm = c + .prepareStatement("SELECT name FROM sqlite_master WHERE type='table' AND name='clientes';");) { + System.out.println("Base de datos conectada"); + // Crear las tablas si es necesario + try (ResultSet rs = pstm.executeQuery()) { + if (rs.next()) { + System.out.println("Existe"); + } else { System.out.println("No existe"); - pstm=c.prepareStatement("create table cliente( - - )"); + // Crear tabla y rellenar datos + try (Statement st = c.createStatement()) { + String creaTabla = "CREATE TABLE clientes (" + + " id integer primary key," + + " nombre text NOT NULL," + + " direccion text NOT NULL)"; + st.executeUpdate(creaTabla); + st.executeUpdate("insert into clientes values " + + "(1, 'Lionel', 'Valencia')," + + "(2, 'Sergi', 'Valencia')," + + "(3, 'Alfredo', 'Valencia')," + + "(4, 'Paco', 'Valencia')," + + "(5, 'Maria', 'Castellón')," + + "(6, 'Pepito', 'Alicante')," + + "(7, 'Luis', 'Elx')," + + "(8, 'Antonia', 'Xàtiva')," + + "(9, 'Carmen', 'Paterna');"); + } } - } catch (Exception e){ + } catch (Exception e) { System.out.println("Error en la consulta"); } - + } catch (Exception e) { - System.out.println("Error al entrar en la BD"); - e.printStackTrace(); + System.out.println("Error al entrar en la BD"); + e.printStackTrace(); + } + + // Ahora mostramos los datos + try (Connection c = DriverManager.getConnection("jdbc:sqlite:mibd.db"); + Statement st = c.createStatement(); + ResultSet rs = st.executeQuery("SELECT * FROM clientes")) { + while (rs.next()) { + System.out.println(rs.getInt(1) + " - " + rs.getString(2) + ":" + rs.getString(3)); + } + + } catch (Exception e) { + System.out.println("Error en la consulta"); } - } } diff --git a/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoSQLite.java b/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoSQLite.java new file mode 100644 index 0000000..7f448cf --- /dev/null +++ b/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoSQLite.java @@ -0,0 +1,177 @@ +package iesthiar.gestorClientesDAO; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import javax.sql.DataSource; + +import org.apache.commons.dbcp2.BasicDataSource; + +public class ClienteDaoSQLite implements Dao { + + // Un DataSource es un intermediario para obtener las conexiones con la base de datos + private DataSource dataSource; + private static ClienteDaoSQLite clienteDaoSQLite=null; + + public static void main(String[] args) { + ClienteDaoSQLite dao=ClienteDaoSQLite.getClienteDaoSQLite(); + if (dao.activa()){ + dao.obtenerTodos().stream().forEach(System.out::println); + } + } + + // El constructor es privado para que no se puedan crear objetos de esta clase. + // Así se implementa el patrón singleton + private ClienteDaoSQLite() { + // Configurar el BasicDataSource con los datos de la base de datos + // Creamos la fuente de datos + BasicDataSource basicDataSource = new BasicDataSource(); + basicDataSource.setUrl("jdbc:sqlite:clientes.sqlite"); + basicDataSource.setUsername("usu"); + basicDataSource.setPassword("clave"); + this.dataSource = basicDataSource; + + // Comprobamos que está creada la tabla + try (Connection conn = dataSource.getConnection(); + PreparedStatement pstmt = conn.prepareStatement("SELECT name FROM sqlite_master WHERE type='table' AND name='clientes'"); + ResultSet rs=pstmt.executeQuery()) { + if (!rs.next()) crearBD(); + }catch (SQLException e) { + e.printStackTrace(); + } + + } + + // Implementación del patrón Singleton. Usamos un método para obtener objetos de la clase. + // Si no existe el objeto, lo creamos, y siempre devolvemos el mismo objeto. Sólo tenemos una instancia de este objeto + public static ClienteDaoSQLite getClienteDaoSQLite(){ + if (clienteDaoSQLite==null) + clienteDaoSQLite=new ClienteDaoSQLite(); + return clienteDaoSQLite; + } + + public void crearBD(){ + try (Connection conn = dataSource.getConnection(); + Statement st = conn.createStatement()){ + + String creaTabla = "CREATE TABLE clientes (" + + " id integer primary key," + + " nombre text NOT NULL," + + " direccion text NOT NULL)"; + st.executeUpdate(creaTabla); + st.executeUpdate("insert into clientes values " + + "(1, 'Lionel', 'Valencia')," + + "(2, 'Sergi', 'Valencia')," + + "(3, 'Alfredo', 'Valencia')," + + "(4, 'Paco', 'Valencia')," + + "(5, 'Maria', 'Castellón')," + + "(6, 'Pepito', 'Alicante')," + + "(7, 'Luis', 'Elx')," + + "(8, 'Antonia', 'Xàtiva')," + + "(9, 'Carmen', 'Paterna');"); + }catch (SQLException e) { + e.printStackTrace(); + } + } + + @Override + public Optional obtener(long id) { + try (Connection conn = dataSource.getConnection(); + PreparedStatement stmt = conn.prepareStatement("SELECT nombre, direccion FROM clientes WHERE id = ?")) { + + stmt.setLong(1, id); + + try (ResultSet rs = stmt.executeQuery()) { + if (rs.next()) { + String nombre = rs.getString("nombre"); + String direccion = rs.getString("direccion"); + + Cliente cliente = new Cliente(id, nombre, direccion); + return Optional.of(cliente); + } + } + } catch (SQLException e) { + e.printStackTrace(); + } + + return Optional.empty(); + } + + @Override + public List obtenerTodos() { + List clientes = new ArrayList<>(); + try (Connection conn = dataSource.getConnection(); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT id, nombre, direccion FROM clientes")) { + + while (rs.next()) { + long id = rs.getLong("id"); + String nombre = rs.getString("nombre"); + String direccion = rs.getString("direccion"); + + Cliente cliente = new Cliente(id, nombre, direccion); + clientes.add(cliente); + } + } catch (SQLException e) { + e.printStackTrace(); + } + return clientes; + } + + @Override + public void guardar(Cliente cliente) { + try (Connection conn = dataSource.getConnection(); + PreparedStatement pst = conn.prepareStatement("insert into clientes(nombre,direccion) values (?,?)")) { + + pst.setString(1, cliente.getNombre()); + pst.setString(2, cliente.getDireccion()); + + pst.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Override + public void actualizar(Cliente cliente) { + try (Connection conn = dataSource.getConnection(); + PreparedStatement pst = conn.prepareStatement("update clientes set nombre=?, direccion=? where id=?")) { + + pst.setString(1, cliente.getNombre()); + pst.setString(2, cliente.getDireccion()); + pst.setLong(3, cliente.getId()); + + pst.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Override + public void borrar(Cliente cliente) { + try (Connection conn = dataSource.getConnection(); + PreparedStatement pst = conn.prepareStatement("delete from clientes where id=?")) { + + pst.setLong(1, cliente.getId()); + + pst.executeUpdate(); + } catch (SQLException e) { + e.printStackTrace(); + } + } + + @Override + public boolean activa() { + try (Connection conn = dataSource.getConnection()) { + return true; + } catch (SQLException e) { + return false; + } + } +} diff --git a/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoSerilizable.java b/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoSerilizable.java deleted file mode 100644 index 56b9fc0..0000000 --- a/src/main/java/iesthiar/gestorClientesDAO/ClienteDaoSerilizable.java +++ /dev/null @@ -1,47 +0,0 @@ -package iesthiar.gestorClientesDAO; - -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class ClienteDaoSerilizable implements Dao{ - - private Map clientes; - - public ClienteDaoSerilizable(){ - // Leer objetos del fichero serializado. - // Fichero se guarda en resources - // Donde dejo los objetos? - } - - @Override - public Optional obtener(long id) { - return Optional.empty(); - } - - @Override - public List obtenerTodos() { - return null; - } - - @Override - public void guardar(Cliente cliente) { - - } - - @Override - public void actualizar(Cliente cliente) { - - } - - @Override - public void borrar(Cliente cliente) { - - } - - @Override - public boolean activa() { - // TODO Auto-generated method stub - throw new UnsupportedOperationException("Unimplemented method 'activa'"); - } -} diff --git a/src/main/java/iesthiar/gestorClientesDAO/gestorClientesControlador.java b/src/main/java/iesthiar/gestorClientesDAO/gestorClientesControlador.java index 2b266d4..794a5c5 100644 --- a/src/main/java/iesthiar/gestorClientesDAO/gestorClientesControlador.java +++ b/src/main/java/iesthiar/gestorClientesDAO/gestorClientesControlador.java @@ -37,7 +37,8 @@ public class gestorClientesControlador implements Initializable { @Override public void initialize(URL location, ResourceBundle resources) { - dao = ClienteDaoMysql.getClienteDaoMysql(); + //dao = ClienteDaoSQLite.getClienteDaoSQLite(); + dao = ClienteDaoSQLite.getClienteDaoSQLite(); if (!dao.activa()) { Alert alerta = new Alert(AlertType.ERROR); alerta.setHeaderText("ERROR GRAVE");