Tomcat 7: JDBC via JNDI using sqlite

First download the sqlite jdbc driver from and copy it into your lib/ folder in your tomcat directory, /usr/share/tomcat7/lib/. Then restart tomcat so it can find your new jar.

Then add a reference to a new jdbc resource in your web/META-INF/context.xml file. It defines a JNDI name, its class type, the driver class name that relates to the jar we just installed above, and a url to connect to the database. In my case I'm pointing to a directory (which must exist) on the file system.

    <Resource name="jdbc/sqlite"

In addition, you have to add the resource in your web.xml file. Note the name is the same the name above.


Now you can make reference to the database in your Java code. This is lifted from the sqlite example page:

Connection conn = null;
try {
    Context ctx = new InitialContext();
    DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/sqlite");
    conn = ds.getConnection();
    Statement statement = conn.createStatement();
try {
    statement.executeUpdate("create table thing(x integer)");
} catch (Exception e) { 
     // Could well be already there
statement.executeUpdate("insert into thing values(42)");
ResultSet rs = statement.executeQuery("select * from thing");
while ( {
writer.println("id = " + rs.getInt(1));
} catch (Exception e) {
} finally {
    try {
        if (conn != null) conn.close();
    } catch (SQLException e) {
java java-jndi java-jdbc sql sql-sqlite java-tomcat

Edit on github
comments powered by Disqus
Click me