Acceder a SQLite a través de JDBC
Ahora vamos a ver como podemos acceder a una base de datos SQLite a través de JDBC. Para ello, voy a hacer uso de del driver JDBCSQlite, así que lo primero que vamos a hacer es descargarlo:
$ wget -c http://files.zentus.com/sqlitejdbc/sqlitejdbc-v056.jar
Después podemos hacer uso del siguiente código de ejemplo para ver que todo funciona:
import java.sql.* ;
class SQLiteJDBCTest {
private static String DATABASE = "base_de_datos.db";
private static String TABLE = "TablaDeLaBaseDeDatos";
public static void main(String args[]) {
try {
// Load the database driver
Class.forName("org.sqlite.JDBC");
// Get a connection to the database
Connection conn = DriverManager.getConnection("jdbc:sqlite:" + DATABASE);
// Print all warnings
for(SQLWarning warn = conn.getWarnings(); warn != null; warn = warn.getNextWarning()) {
System.out.println("SQL Warning:");
System.out.println("State: " + warn.getSQLState());
System.out.println("Message: " + warn.getMessage());
System.out.println("Error: " + warn.getErrorCode());
}
// Get a statement from the connection
Statement stmt = conn.createStatement() ;
// Execute the query
ResultSet rs = stmt.executeQuery("SELECT * FROM " + TABLE);
// Close the result set, statement and the connection
rs.close();
stmt.close();
conn.close();
}
catch(SQLException se) {
System.err.println("SQL Exception:");
// Loop through the SQL Exceptions
while(se != null) {
System.err.println("State: " + se.getSQLState());
System.err.println("Message: " + se.getMessage());
System.err.println("Error: " + se.getErrorCode());
se = se.getNextException();
}
}
catch(Exception e) {
System.err.println(e.toString());
}
}
}
Lo único que habrá que modificar son las variables de clase DATABASE y TABLE. Una vez hecho esto, bastará con compilar y ejecutar para asegurarnos que todo funciona:
$ javac SQLiteJDBCTest.java
$ java SQLiteJDBCTest
java.lang.ClassNotFoundException: org.sqlite.JDBC
Es importante recordar, que para que esto funcione debemos añadir el driver que descargamos al principio al classpath:
$ java -cp .:sqlitejdbc-v056.jar SQLiteJDBCTest
Tags
La teoría es cuando crees saber algo, pero no funciona.
La práctica es cuando algo funciona, pero no sabes por qué.
Los programadores combinan la teoría y la práctica:
Nada funciona y no saben por qué.
