SQLite Java: Create a New Table

Summary: in this tutorial, you will learn how to create a new table in an SQLite database from a Java program using SQLite JDBC Driver.

To create a new table in a specific database, you use the following steps:

  1. First, prepare a CREATE TABLE statement to create the table you want.
  2. Second, connect to the database.
  3. Third, create a new instance of the Statement class from a Connection object.
  4. Fourth, execute the CREATE TABLE statement by calling the executeUpdate() method of the Statement object.

The following program illustrates the steps of creating a table:

import java.sql.DriverManager;
import java.sql.SQLException;

public class Main {

    public static void main(String[] args) {
        // SQLite connection string
        var url = "jdbc:sqlite:my.db";

        // SQL statement for creating a new table
        var sql = "CREATE TABLE IF NOT EXISTS warehouses ("
                + "	id INTEGER PRIMARY KEY,"
                + "	name text NOT NULL,"
                + "	capacity REAL"
                + ");";

        try (var conn = DriverManager.getConnection(url);
             var stmt = conn.createStatement()) {
            // create a new table
            stmt.execute(sql);
        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }
}Code language: Java (java)

How it works.

First, import the classes from java.sql package:

import java.sql.DriverManager;
import java.sql.SQLException;Code language: CSS (css)

Second, declare and initialize a variable that holds a connection string to the my.db database:

var url = "jdbc:sqlite:my.db";Code language: JavaScript (javascript)

Third, construct a CREATE TABLE statement that creates the warehouses table in the sqlite database file:

var sql = "CREATE TABLE IF NOT EXISTS warehouses (" +
  "	id INTEGER PRIMARY KEY," +
  "	name text NOT NULL," +
  "	capacity REAL" +
  ");";Code language: JavaScript (javascript)

Fourth, open a new database connection to the sqlite database using the getConnection() method of the DriverManager class:

var conn = DriverManager.getConnection(url);Code language: JavaScript (javascript)

Fifth, create a Statement class from the Connection object for executing SQL statements:

var stmt = conn.createStatement()Code language: JavaScript (javascript)

We use the try-with-resources to properly close the statement and connection objects.

Sixth, call the execute() statement to execute the CREATE TABLE statement:

stmt.execute(sql);Code language: CSS (css)

Seventh, display the error message if any SQL exception occurs in the catch block:

System.out.println(e.getMessage());Code language: CSS (css)

Finally, run the program to create the warehouses table.

Summary

  • Call the execute() method of the Statement object to run the CREATE TABLE statement to create a new table in the SQLite database.
Was this tutorial helpful ?