Java and SQLite – Selecting Data

When performing an operation on an SQLite database, such as selecting, inserting, updating and deleting data, the first thing that needs to be done is to connect to the database, as previously described.

In order to retrieve data, as well as insert, update and delete data, from an SQLite database, SQL, or Structured Query Language needs to be used, more details of which can be found here. Retrieving data is done via the ‘Select’ statement.

The following table of data, called ‘person’, will be used in the example below for selecting data.

id firstname lastname title dob
1 Bob Smith Mr 1980-01-20
2 George Jones Mr 1997-12-15
3 Fred Bloggs Mr 1975-05-07
4 Alan White Mr 1989-03-20

Note that, in an SQLite database there is no specific datatype for storing dates. One option, although not the only option, is to store them as text in the format YYYY-MM-DD (four digit year, two digit month and two digit day), which allows them to be sorted if necessary. Once the date has been extracted from the database, it can be manipulated programmatically in to the desired format.

The example below selects four items of data from the ‘person’ table, in last name, first name and date of birth order. The resulting data is stored in a variable, which is then used in a ‘while’ loop to output details of each record to the console in the format: “id: lastname, firstname (dob)”. Where the person information is being output, ‘%s’ is a place holder for an item of data, so the first ‘%s’ is for the ‘id’, the second is for the ‘lastname’ and so on. The ‘%n’ forces a new line in the console before the details of the next person are displayed.

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

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()) {

            // Confirm incorrect database location and stop program execution.
            System.out.println("Error locating database.");
            System.exit(0);

        }

        try {

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

        } catch (SQLException e) {

            // Confirm unsuccessful connection and stop program execution.
            System.out.println("Database connection unsuccessful.");
            System.exit(0);

        }

        // SQL to select data from the person table.
        String sqlSelect = 
                "SELECT id, firstname, lastname, dob " +
                "FROM person " +
                "ORDER BY lastname, firstname, dob";

        try {

            // Execute query.
            Statement statement  = connect.createStatement();
            ResultSet results    = statement.executeQuery(sqlSelect);

            // Display person information in the console.
            while (results.next()) {

                System.out.printf("%s: %s, %s (%s/%s/%s)%n",
                        results.getInt("id"),
                        results.getString("lastname"),
                        results.getString("firstname"),
                        results.getString("dob").substring(8,10),
                        results.getString("dob").substring(5,7),
                        results.getString("dob").substring(0,4));

            }

            // Close the statement and database connection.
            statement.close();
            connect.close();

        } catch (SQLException e) {

            // Confirm error retrieving person information and quit.
            System.out.println("Error retrieving person information.");
            System.exit(0);

        }

    }

}

The resulting output to the console is as follows.

3: Bloggs, Fred (07/05/1975)
2: Jones, George (15/12/1997)
1: Smith, Bob (20/01/1980)
4: White, Alan (20/03/1989)

Often it isn’t necessary to return all records from a database table. Where this is the case, parameters need to be introduced into the query. In the following example, the records returned are limited to those with a date of birth between 1 January 1980 and 31 December 1989. Within the SQL, question marks are used to signify that parameters need to be incorporated. The parameter values are then bound into the SQL statement before it is executed. Binding the parameters in this way helps prevent SQL injection, where hackers try to insert malicious code to either do damage to the database or access more data than should be allowed.

import java.io.File;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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()) {

            // Confirm incorrect database location and stop program execution.
            System.out.println("Error locating database.");
            System.exit(0);

        }

        try {

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

        } catch (SQLException e) {

            // Confirm unsuccessful connection and stop program execution.
            System.out.println("Database connection unsuccessful.");
            System.exit(0);

        }

        // Query parameters.
        String dobLower = "1980-01-01";
        String dobUpper = "1989-12-31";

        // SQL to select data from the person table.
        String sqlSelect = 
                "SELECT id, firstname, lastname, dob " +
                "FROM person " +
                "WHERE dob BETWEEN ? AND ? " +
                "ORDER BY lastname, firstname, dob";

        try {

            // Create statement and bind the parameters.
            PreparedStatement statement = connect.prepareStatement(sqlSelect);
            statement.setString(1, dobLower);
            statement.setString(2, dobUpper);

            // Execute query.
            ResultSet results = statement.executeQuery();

            // Display person information in the console.
            while (results.next()) {

                System.out.printf("%s: %s, %s (%s/%s/%s)%n",
                        results.getInt("id"),
                        results.getString("lastname"),
                        results.getString("firstname"),
                        results.getString("dob").substring(8,10),
                        results.getString("dob").substring(5,7),
                        results.getString("dob").substring(0,4));

            }

            // Close the statement and database connection.
            statement.close();
            connect.close();

        } catch (SQLException e) {

            // Confirm error retrieving person information and quit.
            System.out.println("Error retrieving person information.");
            System.exit(0);

        }

    }

}

The resulting output to the console is as follows.

1: Smith, Bob (20/01/1980)
4: White, Alan (20/03/1989)