Wednesday, November 22, 2006

SQLite 3 and Java

The other day, I went off about how great SQLite was and everything, as well as how to use it with Ruby. Today I'll tell you how to use SQLite with Java. Just download SQLite JDBC drivers from here. Figure out where sqlite.jar and sqlite_jni.dll (native file) are, allow your java program to find them, and then access your sqlite database using JDBC. If you aren't familiar with jni and you're using windows, you can throw that DLL file into C:/WINDOWS. Support is cake for anyone who has used Java before. The documentation for the SQLite JDBC project can be found over here. As I said before, SQLite is a good database, especially for personal projects (where running your own database server is overkill) and quick testing. Also, the SQLite SQL implementation supports more than the in-memory database HSQLdb does, which I feel is the other good alernative. I'm liking SQLite more than HSQLdb. But I'm probably especially whiny about HSQLdb right now, since it didn't support the SQL case-when statement that I wanted to use for my last project.

As for examples... well, it's JDBC: the beauty of it is I don't need to give examples. But since I have examples, here's some very brief code to create a connection. If you don't know JDBC, read the JDBC documentation from Sun, it's probably worth knowing regardless of what you program for. With that, following this brief example (for which requires importing java.sql.Connection and having sqlite.jar and sqlite_jni.dll on your paths), I'm all done.

// Load the Database Engine JDBC driver
Class.forName( "SQLite.JDBCDriver");

// connect to the database
Connection conn = DriverManager.getConnection( "jdbc:sqlite:/filename", "", "" );

//close the connection. So pointless.
conn.close();

1 comment:

Unknown said...

Visit http://www.javaworkspace.com/connectdatabase/connectSQLite.do to connect java with SQLite database via JDBC