Skip to content

9.10 Trabajar con Sqlite

Para poder trabajar en casa, vamos a utilizar Sqlite que es un una base de datos sencilla que se guarda en un único archivo en disco.

Lo primero es instalar SQLite, en Ubuntu:

sudo apt install sqlite3

Si queréis hacerlo en Windows, podéis seguir las instrucciones en http://www.sqlitetutorial.net/download-install-sqlite/.

Para poder trabajar en Java, hemos de descargar el conector, desde https://github.com/xerial/sqlite-jdbc/releases.

Lo primero que hemos de hacer es crear una base de datos, desde la línea de comandos. Para ello nos situamos en el directorio del proyecto y la creamos en el directorio bd mediante el siguiente comando:

1
2
3
4
5
6
7
cd directorio-del-proyecto
# directorio-del-proyecto: EjerciciosJava

mkdir bd
cd bd

sqlite network.bd

1. Instalar SQLiteStudio

Podemos instalar una aplicación gráfica como SQLiteStudio para trabajar (más fácilmente) con SQLite desde estos enlaces:

bluej 0

Mediante estos comandos creamos una base de datos en disco llamada prudb.bd.

CREATE TABLE usuarios (
 id INTEGER PRIMARY KEY AUTOINCREMENT,
  nombre VARCHAR(50) NOT NULL,
  apellidos VARCHAR(255) NOT NULL
);


CREATE TABLE posts (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  texto VARCHAR(255) NOT NULL,
  likes INTEGER NOT NULL,
  fecha timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  id_usuario INTEGER NOT NULL,
  FOREIGN KEY (id_usuario) REFERENCES usuarios(id)
);


CREATE TABLE comentarios (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  texto VARCHAR(255) NOT NULL,
  fecha timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  id_usuario INTEGER  NOT NULL,
  id_post INTEGER  NOT NULL,
  FOREIGN KEY (id_usuario) REFERENCES usuarios(id),
  FOREIGN KEY (id_post) REFERENCES posts(id)
);

Ahora deberemos añadir la librería JDBC (fichero .jar) a nuestro proyecto. Para ello copia el archivo mysql-connector-java-x.x.x.jar (en Ubuntu se encuentra en la ruta /usr/share/java) en JAVA PROJECTS -> Referenced Libraries de VS Code*:

agregar libreria jdbc

Y ahora modificamos DatabaseConnection:

 String host = "jdbc:sqlite:src/main/resources/network";
 con = java.sql.DriverManager.getConnection( host);

Y hacemos una prueba para ver si funciona:

import java.sql.SQLException; 

public class Main { 

      public static void main(String[] args) { 
          // TODO Aute-generated mettod stub 
          Test t = new Test(); 
          t.insertUser(); 

          try {
              t.getellUsers(); 
          } catch (SQLException sqle) { 
              System.out.println(sqle.getMessage()); 
          }
          t.closeConnection(); 
      }
}

Y este debe ser el resultado:

Conexión realizada
1   Janet   Espinosa

2. Ejemplos

Vamos a crear una pequeña base de datos para Empleados en Sqlite:

Num Nombre Departamento Edad Sueldo
1 Andreu 10 32 1000.00
2 Bernat 20 28 1200.00
3 Claudia 10 26 1100.00
4 Damià 10 40 1500.00

Primero creamos un nuevo Proyecto en VSCode llamado EmpleadosBD y le añadimos la librería sqlite al build path.

Creamos también la base de datos mediante la línea de comandos:

1
2
3
4
cd directorio-del-proyecto
mkdir bd
cd bd
sqlite empleados.bd

Copiamos el archivo DatabaseConnection.java del anterior proyecto y modificamos la cadena de conexión:

String host = "jdbc:sqlite:./bd/empleados.bd";
con = java.sql.DriverManager.getConnection( host);

2.1. Crear tabla

Creamos una clase CreateTable para poder crear la tabla:

import java.sql.SQLException; 
import java.sql.Statement; 

public class CreateTable {
    static java.sql.Connection con = DatabaseConnection.getInstance().getConnection(); 

    public static vold main(String[] args) { 
        Statement st = null; 
        String sql = "CREATE TABLE empleados ( " + 
                     " num INTEGER PRIMARY KEY, " + 
                     " nombre VARCHAR(255), " +
                     " departamento INTEGER, " + 
                     " edad INTEGER, " + 
                     " sueldo REAL);"; 
        try { 
            st = con.createStatement(); 
            st.executeUpdate(sql); 
        } catch (sQLException ex) { 
            system.out.println("Error " + ex.getMessage()); 
        } finally {
            try {
                if (st != null && !st.isClosed()) {
                    st.close(); 
                }
            } catch (SQLException ex) { 
                system.out.println ("No se ha podido cerrar el Statement por alguna razón");
            }
            try {
                if (con != null && !con.isClosed()) {
                    con.close(); 
                }
            } catch (SQLException ex) { 
                system.out.println ("No se ha podido cerrar el Statement por alguna razón");
            }
        }
    }
}

2.2. Insertar datos

Y creamos otra para insertar datos. Esta vez lo haremos con PreparedStatement:

import java.sql.PreparedStatement; 
import java.sql.SQLException; 

public class InsertData { 
  static java.sql.Connection con = DatabaseConnection.getInstance().getConnection(); 

  public static void main(String[] args) { 
      PreparedStatement st = null;
      String sql = "INSERT INTO empleados (num, nombre, departamento, edad, sueldo) VALUES (?, ?, ?, ?, ?)"; 
      try { 
          st = con.prepareStatement(sql); 
          st.setlnt(1, 1); 
          st.setString(2, "Andreu"); 
          st.setlnt(3, 10); 
          st.setlnt(4, 32); 
          st.setDouble(5, 1000.0); 
          st.executeUpdate(); 

          st.setlnt(1, 2); 
          st.setString(2, "Bernat"); 
          st.setlnt(3, 20); 
          st.setlnt(4, 28); 
          st.setDouble(5, 1200.0); 
          st.executeUpdate(); 

          st.setlnt(1, 3); 
          st.setString(2, "Claudia"); 
          st.setlnt(3, 10); 
          st.setlnt(4, 26);
          st.setDouble(5, 1400.0); 
          st.executeUpdate(); 

          st.setlnt(1, 4); 
          st.setString(2, "Damián"); 
          st.setlnt(3, 10); 
          st.setlnt(4, 40); 
          st.setDouble(5, 1300.0); 
          st.executeUpdate(); 

      } catch (SQLException ex) { 
          System.out.println("Error " + ex.getMessage()); 

      } finally { 
          try { 
              if (st != null && !st.isClosed()) { 
                  st.close(); 
              } 
          } catch (SQLException ex) { 
              System.out.println("No se ha podido cerrar el Statement por alguna razón"); 
          } 

          try { 
              if (con != null && !con.isClosed()) { 
                  con.close(); 
              } 
          } catch (SQLException ex) { 
              System.out.println("No se ha podido cerrar Connection por alguna razón"); 
          } 
      }
  }
}

Esta es la versión con Statement:

import java.sql.Statement; 
import java.sql.SQLException; 

public class InsertDataStatement { 
  static java.sql.Connection con = Databaseconnection.getInstance().getConnection(); 

  public static void main(String[] args) { 
      Statement st = null; 
      String sql = ""; 

      try { 
          st = con.createStatement();
          sql = "INSERT INTO EMPLEADOS (num, nombre, departamento, edad, sueldo) VALUES (5, 'Arturo', 10, 32, 1088.8)"; 
          st.executeUpdate(sql); 

          sql = "INSERT INTO EMPLEADOS (num, nombre, departamento, edad, sueldo) VALSES (6, 'Juan', 28, 28, 1280.8)";
          st.executeUpdate(sql); 

          sql = "INSERT INTO EMPLEADOS (num, nombre, departamento, edad, sueldo) VALUES (2, 'Martín', 10, 26, 1488.8)"; 
          st.executeUpdate(sql); 

      } catch (SQLEXCeptiOn ex) {
          System.ont.println("Error: "+ ex.getMesSege());

      } finally {
          try { 
              if (st != null && !st.isClosed()) {
                  st.close(); 
              }
          } catch (SQLException ex) { 
              System.out.println("No se ha podido cerrar el Statement por alguna razón");
          }
          try { 
              if (con != null && !con.isClosed()) {
                  con.close(); 
              }
          } catch (SQLException ex) { 
              System.out.println("No se ha podido cerrar el Statement por alguna razón");
          }
      }
  }
}

Consultar datos

Creamos una clase getAllEmpleados que nos devuelva todos los empleados:

import java.sql.Resultset; 
import java.sql.SQLException; 
import java.sql.Statement; 

public class getAllEmpleados { 
    static java.sql.Connection con = DatabaseConnection.getInstance().getConnection(); 

    public static void main(String[] args) { 
        Statement st = null; 
        Resultset rs = null; 

        try {
            st = con.createStatement(); 
            rs = st.executeQuery("SELECT * FROM empleados"); 
            System.out.println("Núm. \tNombre \tDep \tEdad \tSueldo"); 
            System.out.println("------------------------------------------");
            while (rs.next()){ 
                System.out.print(rs.getInt(1) + "\t"); 
                system.out.print(rs.getString(2) + "\t"); 
                system.out.print(rs.getInt(3) + "\t"); 
                system.out.print(rs.getInt(4) + "\t"); 
                System.out.println(rs.getDouble(5)); 

        } catch(SQLException e) { 
                System.out.println("Se ha producido un error al leer los usuarios " + e.getMessage());           

        } finally { 
            try { 
                //Siempre se debe cerrar todo lo abierto 
                if (st != null) {
                    st.close(); 
                }
            } catch (java.sql.SQLException ex){
                System.out.println("Se ha producido un error: " + ex.getMessage()); 
            }
            try { 
                //Siempre se debe cerrar todo lo abierto 
                if (rs != null) {
                    rs.close(); 
                }
            } catch (java.sql.SQLException ex){
                System.out.println("Se ha producido un error: " + ex.getMessage()); 
            }
        }
    }
}

Modificar datos

Ahora modificamos los datos. Simplemente aumentamos el sueldo un 5% y modificamos el departamento del empleado 3, poniéndole el departamento 3.

import java.sql.Statement; 
import java.sql.SQLException; 

public class ModifyData { 
  static java.sql.Connection con = Databaseconnection.getInstance().getConnection(); 

  public static void main(String[] args) { 
      Statement st = null; 
      String sql = "";
      try {
          st = con.createStatement(); 
          sql = "UPDATE EMPLEADOS SET sueldo = sueldo * 1.05";
          st.executeUpdate(sql);

          sql = "UPDATE EMPLEADOS SET departamento = 20 WHERE num = 3";
          st.executeUpdate(sql); 

      } catch (SQLException ex) { 
          system.out.printlnr("Error "+ ex.getMessage());

      } finally { 
          try { 
              if (st != null && !st.isClosed()) { 
                  st.close(); 
              } 
          } catch (SQLException ex) { 
              system.out.println("No se ha podido cerrar el Statement por alguna razón");
          }
          try { 
              if (con != null && !con.isClosed()) { 
                  con.close(); 
              } 
          } catch (SQLException ex) { 
              system.out.println("No se ha podido cerrar el Statement por alguna razón");
          }
      }
  }
}