SQLite Java: Create a New SQLite Database

Summary: in this tutorial, we will show you how to create a new SQLite database using the Java SQLite JDBC.

To create a new SQLite database from the Java application, you follow these steps:

  1. First, specify the database name and its location e.g., c:\sqlite\db\test.db
  2. Second, connect to the database via SQLite JDBC driver.

When you connect to an SQLite database that does not exist, it automatically creates a new database. Therefore, to create a new database, you just need to specify the database name and connect to it.

The following program creates a new SQLite database named test.db in the folder c:\sqlite\db.

package net.sqlitetutorial;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 *
 * @author sqlitetutorial.net
 */
public class Main {

    /**
     * Connect to a sample database
     *
     * @param fileName the database file name
     */
    public static void createNewDatabase(String fileName) {

        String url = "jdbc:sqlite:C:/sqlite/db/" + fileName;

        try (Connection conn = DriverManager.getConnection(url)) {
            if (conn != null) {
                DatabaseMetaData meta = conn.getMetaData();
                System.out.println("The driver name is " + meta.getDriverName());
                System.out.println("A new database has been created.");
            }

        } catch (SQLException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        createNewDatabase("test.db");
    }
}Code language: Java (java)

Now we run the program and see the following output:

run:
The driver name is SQLiteJDBC
A new database has been created.
BUILD SUCCESSFUL (total time: 0 seconds)Code language: Shell Session (shell)

The test.db should be created in the c:\sqlite\db\ folder. You can check it to ensure that the database has been created.

Was this tutorial helpful ?