Using SQLite in Java

By xngo on June 23, 2019

The code below shows how to use Java to connect to SQLite and then create a simple table.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
 
public class SqliteConnection {
 
    public static void main(String[] args) {
 
        // Where your database is or will be stored.
        String databaseURL = "jdbc:sqlite:/C:/temp/tmpSqlite.db";
 
        try {
            // Load the sqlite-JDBC driver using the current class loader
            Class.forName("org.sqlite.JDBC");
 
            // Create a database connection
            Connection connection = DriverManager.getConnection(databaseURL);
            Statement statement = connection.createStatement();
 
            // Create a Person table.
            statement.executeUpdate("CREATE TABLE Person(first_name TEXT, last_name TEXT, age INT)");
 
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Output

If you have SQLite installed, you can run the following command to verify that Person table is created.

sqlite3 C:\temp\tmpSqlite.db ".schema"

It will output the following:

CREATE TABLE Person(first_name TEXT, last_name TEXT, age INT);

Github

  • https://github.com/xuanngo2001/java-sqlite/blob/master/src/net/xngo/tutorial/java/sqlite/SqliteConnection.java

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.