Pages

Monday, January 14, 2013

A Serverless, Zero-Configuration Database Solution : SQLite




Most software need saving data. Sometimes that data is predicted to be small and hundreds or thousands of transactions on it will not be needed at the same time. But you will need some SQL-like operations on that data, because some modifications can be difficult and time consuming with regular file operations. At that time, SQLite becomes a very practical solution to this situation.

It started as a C/C++ library (on http://www.sqlite.org/) but it also has Xerial jdbc project for Java (on http://www.xerial.org/trac/Xerial/wiki/SQLiteJDBC and https://bitbucket.org/xerial/sqlite-jdbc lastly). We will tell some details of Java JDBC project here. Some critical properties are:

  • You need only one jar file and adding it to the classpath.
Download latest jar (from here: https://bitbucket.org/xerial/sqlite-jdbc/downloads) and add to the classpath. 
  • Needs one line of code to start using.
Class.forName("org.sqlite.JDBC"); line is enough for activating driver.
  • It creates one database file per schema at the place which you will determine.
Connection con = DriverManager.getConnection("jdbc:sqlite:mydb.db"); line creates "mydb.db" file as database file on the root of your project and creates a connection for DB operations.
  • Supports a general formed JDBC SQL syntax with a useful JDBC API.
Some code examples are shown below (connection opening/closing statements are not included each time for simplifying statements):

  1. // opening connection
  2. Connection con = DriverManager.getConnection("jdbc:sqlite:person.db");
  3. Statement stat = con.createStatement();

  4. // closing connection
  5. con.close();
  6.  
  7. // creating table
  8. stat.executeUpdate("create table person(id INT, name varchar(30));");
  9. // dropping table
  10. stat.executeUpdate("drop table if exists person");
  11. // inserting data
  12. PreparedStatement prep = con.prepareStatement("insert into person values(?,?);");
  13. prep.setInt(1, 1);
  14. prep.setString(2, "andy brown");
  15. prep.execute();
  16. // selecting data
  17. ResultSet res = stat.executeQuery("select * from person");
  18. while (res.next()) {
  19.      System.out.println(res.getString("id") + " " + res.getString("name"));
  20. }
  21. // updating data
  22. PreparedStatement prep = con.prepareStatement("update person set name = ? where id = ?;");
  23. prep.setString(1, "andy black");
  24. prep.setInt(2, 1);
  25. prep.execute();

For more detailed examples about SQL syntax, please take a look at:
http://docs.oracle.com/javase/tutorial/jdbc/index.html

1 comment: