SQLite and a JDBC Connection Pool in a Java Web App
A whole database in one file, studyeasy.db, and a Java web app that talks to it: one HikariCP pool, a @WebListener that opens it and runs schema.sql at startup, and a /db-check servlet that borrows a connection.
What you will learn
- Explain why a SQLite database is just one file
- Set up one HikariCP connection pool for the whole app
- Open the pool and create the table at startup with a @WebListener
- Borrow a connection, run a COUNT query and give the connection back
Before you start
- The Servlet Request Lifecycle
- Basic SQL: CREATE TABLE and SELECT
The Users app in this section stores its data in SQLite, the simplest database to start with. The whole database is one file, studyeasy.db. There's no server, no port, and no username or password. It's fast, and you'll find this kind of database inside a lot of mobile apps. This article connects a servlet app to that file.
The table comes from the app
The app carries its own table definition in src/main/resources/schema.sql and runs it at every start:
-- The users table for the whole section. The app runs this file at every
-- start: IF NOT EXISTS makes every start after the first one do nothing.
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(100) NOT NULL,
email VARCHAR(150) NOT NULL UNIQUE
)
Three columns: an id that counts up on its own, a name, and an email that must be unique. Because of IF NOT EXISTS, the first start creates the table and every later start leaves it alone.
Borrow a connection, give it back
Opening a database connection is slow. So instead of one new connection per request, the app keeps a pool: a few connections opened once and lent out. It's like a library. You borrow a book, return it, and the next person reads the same copy.
One pool for the app
package org.studyeasy.web.db;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
// One pool for the whole app: connections are opened once,
// then lent out and given back, instead of a new one per request.
public class Database {
private static final HikariDataSource POOL = createPool();
private static HikariDataSource createPool() {
HikariConfig config = new HikariConfig();
// the whole database is one file: studyeasy.db in your home folder
config.setJdbcUrl("jdbc:sqlite:" + System.getProperty("user.home") + "/studyeasy.db");
// name the driver: a web app's own jars are not on the JVM's path
config.setDriverClassName("org.sqlite.JDBC");
config.setMaximumPoolSize(5);
return new HikariDataSource(config);
}
public static DataSource getDataSource() {
return POOL;
}
// runs schema.sql (src/main/resources): the tables the app needs
public static void createTables() {
try (InputStream in = Database.class.getResourceAsStream("/schema.sql");
Connection con = POOL.getConnection();
Statement st = con.createStatement()) {
String sql = new String(in.readAllBytes(), StandardCharsets.UTF_8);
st.executeUpdate(sql);
} catch (IOException | SQLException e) {
throw new IllegalStateException("Could not create the tables", e);
}
}
public static void close() {
POOL.close();
}
}
- The JDBC URL points at
studyeasy.dbin your home folder. You never create that file: the SQLite driver creates it on the first connect. - The driver class is named explicitly, because a web app's own jars are not on the JVM's normal path.
- The pool holds at most five connections. For a small file database, that's plenty.
getDataSource()is where everyone asks for a connection.createTables()runsschema.sql.close()closes the pool.
This needs three jars in pom.xml: the SQLite driver, the pool and a logger.
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.53.4.0</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>7.1.0</version>
<!-- the connection pool -->
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.0.20</version>
<!-- prints the pool's log lines on Tomcat -->
</dependency>
Open at start, close at stop
package org.studyeasy.web.db;
import jakarta.servlet.ServletContextEvent;
import jakarta.servlet.ServletContextListener;
import jakarta.servlet.annotation.WebListener;
@WebListener // the server calls it when the app starts and stops
public class DatabaseListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// open the pool now: a wrong path fails at startup,
// not on a user's first click
Database.getDataSource();
System.out.println("pool ready");
// the users table, if this is a brand-new studyeasy.db
Database.createTables();
System.out.println("tables ready");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// close every pooled connection when the app stops or redeploys
Database.close();
System.out.println("pool closed");
}
}
With @WebListener, the server calls this class itself when the app starts and stops; you never call it. contextInitialized opens the pool right away, so a wrong path fails at startup instead of on a user's first click, then makes sure the table exists. contextDestroyed closes every pooled connection when the app stops or redeploys.
Borrow, query, give back
package org.studyeasy.web;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.studyeasy.web.db.Database;
@WebServlet("/db-check")
public class DbCheckServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// borrow a connection from the pool; close() gives it back
try (Connection con = Database.getDataSource().getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT COUNT(*) FROM users")) {
rs.next();
int count = rs.getInt(1);
int version = con.getMetaData().getDatabaseMajorVersion();
System.out.println("db-check: " + count + " users");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><head><title>Database check</title>");
out.println("<link rel=\"stylesheet\" href=\"css/style.css\">");
out.println("</head><body><main><h1>Database check</h1>");
out.println("<p>Connected to SQLite " + version + "</p>");
out.println("<p>Rows in users: " + count + "</p>");
out.println("</main></body></html>");
} catch (SQLException e) {
throw new ServletException("Database check failed", e);
}
}
}
getConnection()borrows from the pool. Because it's inside thetry (...)brackets, it is closed for you at the end, which means it goes back to the pool.SELECT COUNT(*) FROM userscomes back as aResultSet.rs.next()moves to the first row andgetInt(1)reads the count.getMetaData()lets you ask the database about itself, which is where the version number comes from.
Start the app, open /db-check, then stop it. The log:
pool ready
tables ready
db-check: 0 users
pool closed
And the browser shows "Connected to SQLite 3" and "Rows in users: 0". The table is empty, which is exactly right for now.
Common mistakes
- Removing
IF NOT EXISTSfromschema.sql. The first start creates the table; the second fails at startup with "table users already exists", and every URL is a 404. - Opening a new connection per request instead of using the pool. It works, but slowly.
- Forgetting to close a connection. Outside try-with-resources, a borrowed connection never returns, and after five the pool runs dry.
Quick recap
| Piece | Job |
|---|---|
studyeasy.db | the whole database, one file |
Database | one HikariCP pool for the app |
DatabaseListener | opens the pool and creates the table at start, closes at stop |
DbCheckServlet | borrows a connection and counts the rows |
Next, put rows in the table in Users CRUD 1: add and list with a DAO.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
MVC and the Front Controller With Servlets and JSP
A Book model, a BookController servlet and a books.jsp view behind WEB-INF show MVC in plain Java. Then one servlet on /app/* becomes a front controller, the idea Spring's DispatcherServlet grew from.
Forms With JSP and Servlets: Handle the POST and Validate on the Server
Post a sign-up form straight to a JSP and anything gets accepted. Post it to a servlet instead: doPost checks name and email, forwards back with errors and the typed values, or on to the welcome page.
Mini App With Servlets and JSP: Login, Logout and a Shared Web Template
Four pages and one template: a login form that posts to a servlet, a session that remembers the user, a filter that guards home.jsp and account.jsp, and a logout that ends it, plus when each step forwards or redirects.
Users CRUD With Servlets and JSP, Part 1: Add and List Through a DAO
Fill an empty users table from a form and list every row: UserController picks the page, UserDao holds all the SQL, SaveUserServlet inserts and redirects, and a JSTL table shows the rows. Plus why every value goes in as a ?.
