Java JDBC using SQLite/Connecting

Assuming that your classpath is now established, and your JDK is ready to go, we can have a quick and dirty attempt to throw together a very simple database with only one table in it. As this is something of a disposable 'HelloWorld' mini-app on steroids, let's call it 'HelloDatabase'.

You really need to know one thing about the JDBC driver: its registered DriverName. For SqlLite this is:


 * org.sqlite.JDBC

This value is used to register the driver in Java. Different JDBC drivers for different database implementations have different registered DriverNames. While it is entirely possible to discover DriverNames from the containing jar file(s) programatically, this lies outside the scope of this document and they can be looked up fairly quickly on the Internet e.g. at.

Now we come to constructing the URL string which is used in establishing the connection to the database. Different JDBCs for different database types have different URL definitions; the SqlLite URL string really just needs to know that it is a jdbc of the type 'sqlite' and the name of the target database which we wish to use. If for example we wish to connect to a new database called order.db we would need to compose a string comprised of the string 'jdbc', the database type name, in this case 'sqlite' plus the name of the database, separated by colons, i.e.:


 * jdbc:sqlite:order.db

other examples


 * jdbc:sqlite://dirA/dirB/dbfile
 * jdbc:sqlite:/DRIVE:/dirA/dirB/dbfile
 * jdbc:sqlite:///COMPUTERNAME/shareA/dirB/dbfile

an in-memory option is also available.

As a minimal set of imports for this mini-app (and for most simple JDBC connectors), you will want the following set of imports available as shown in the following code. The two .*MetaData imports are useful and often necessary for debugging and investigative purposes, as well as being handy for abstraction and ultimate reduction in the quantity of hard code that your programs will require.

You should now also find that you have a file called hello.db in your working directory, (or whatever else you called it in the database name component for the URL). If you attempt to run this code more than once, you will get a SQL Exception error since you will be trying to create a table that already exists; you can delete the .db file, or use SqLite to drop the table, or insert a new String with a drop table statement in it and use stmt.executeUpdate to run the drop string before attempting to create the table...


 * Next Page:  ../Improving/
 * Previous Page:  ../Preparation/