Java and SQLite Introduction

SQLite is a database that can be used in conjunction with Java to create desktop, web and console based application, as well as Android based mobile apps. It can be used to store data, as well as configuration information. Java, together with SQL, can be used to query the data stored within an SQLite database, as well as insert, update and delete the data. In order for this to be possible, the SQLite JDBC Driver needs to be used.

Connecting to an SQLite Database

In order to access data within an SQLite database using Java, a connection to the database must first be established. Below is an example of how this can be achieved. Unlike other databases, such as MySQL, SQLite does not require a separate server process, but instead exists as a standalone file, that can be embedded directly into an application. A username and password are also not required to access the database, instead file permissions are used to limit access to it.

import java.io.File;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class DemoSQLite {

    public static void main(String[] args) {

        // Database and connection variables.
        File database = new File("C://Demo//testDB.db");
        Connection connect = null;

        // Check if database file exists.
        if (!database.isFile()) {

            // Message confirming incorrect database location.
            System.out.println("Error locating database.");

            // Stop program execution.
            System.exit(0);

        }

        try {

            // Connect to database.
            connect = DriverManager.getConnection("jdbc:sqlite:" + database.getPath());

            // Message confirming successful database connection.
            System.out.println("Database connection successful.");

        }  catch (SQLException e) {

            // Message confirming unsuccessful database connection.
            System.out.println("Database connection unsuccessful.");

            // Stop program execution.
            System.exit(0);

        }

    }

}

Firstly, in this example, a check is made to see if the database file actually exists. If it doesn’t, a message is displayed and execution of the program is halted. Note that here, the database resides in a separate location to the program, however, for an Android application, it would need to be embedded as a resource within the application itself. If successfully found, an attempt is made to connect to the database, which is enclosed in a ‘try-catch’ block. The ‘try-catch’ block is used to catch any exceptions that arise in trying to connect to the database and deal with them in a user friendly manner. Again, an ‘exit’ statement is used after the confirmation of an unsuccessful database connection, which stops execution of the program completely.