generated from programacionThiar/plantilla_iesthiar_javafx
con SQLite
This commit is contained in:
BIN
clientes.sqlite
Normal file
BIN
clientes.sqlite
Normal file
Binary file not shown.
@@ -4,26 +4,42 @@ 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';");
|
||||
) {
|
||||
// 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()){
|
||||
try (ResultSet rs = pstm.executeQuery()) {
|
||||
if (rs.next()) {
|
||||
System.out.println("Existe");
|
||||
}
|
||||
else {
|
||||
} 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");
|
||||
}
|
||||
|
||||
@@ -32,5 +48,16 @@ public class EjemploSQLite {
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
177
src/main/java/iesthiar/gestorClientesDAO/ClienteDaoSQLite.java
Normal file
177
src/main/java/iesthiar/gestorClientesDAO/ClienteDaoSQLite.java
Normal file
@@ -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<Cliente> {
|
||||
|
||||
// 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<Cliente> 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<Cliente> obtenerTodos() {
|
||||
List<Cliente> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package iesthiar.gestorClientesDAO;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
public class ClienteDaoSerilizable implements Dao<Cliente>{
|
||||
|
||||
private Map<Long,Cliente> clientes;
|
||||
|
||||
public ClienteDaoSerilizable(){
|
||||
// Leer objetos del fichero serializado.
|
||||
// Fichero se guarda en resources
|
||||
// Donde dejo los objetos?
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Cliente> obtener(long id) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Cliente> 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'");
|
||||
}
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
Reference in New Issue
Block a user