DEV Community

Prabesh Shrestha
Prabesh Shrestha

Posted on

Connecting SQLite Database in Java

SQLite is a lightweight, self-contained database engine that is widely used in various applications due to its simplicity and versatility.

Step 1: Download SQLite JDBC Driver

Before you can connect to an SQLite database in Java, you need to download the SQLite JDBC driver. You can easily find the latest version of the SQLite JDBC driver online and download the JAR file.

Step 2: Add SQLite JDBC Driver to Your Java Project

Once you've downloaded the SQLite JDBC driver, you need to add it to your Java project's classpath. You can do this by including the JAR file in your project's build path using your IDE or by manually adding it to the lib directory of your project.

Step 3: Create an SQLite Database

Next, you'll need to create an SQLite database file (.db) using a tool like SQLiteStudio or the SQLite command-line interface. Make sure to note the location of the database file as you'll need it to establish a connection from your Java code.

Step 4: Connect to the SQLite Database in Java

Now that you have the SQLite JDBC driver and database file set up, you can establish a connection to the database in your Java code. Here's a simple example of how to do this:

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

public class SQLiteConnection {
    public static void main(String[] args) {
        Connection connection = null;
        try {
            // Register SQLite JDBC driver
            Class.forName("org.sqlite.JDBC");

            // Connect to the SQLite database
            String url = "jdbc:sqlite:/path/to/your/database.db";
            connection = DriverManager.getConnection(url);

            if (connection != null) {
                System.out.println("Connected to the SQLite database.");
                // Perform database operations here
            }
        } catch (ClassNotFoundException e) {
            System.out.println("SQLite JDBC driver not found.");
            e.printStackTrace();
        } catch (SQLException e) {
            System.out.println("Unable to connect to the SQLite database.");
            e.printStackTrace();
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.out.println("Error closing the connection.");
                e.printStackTrace();
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Replace "/path/to/your/database.db" with the actual path to your SQLite database file.

Step 5: Perform Database Operations

Once you've established a connection to the SQLite database, you can perform various database operations such as querying data, inserting, updating, or deleting records using SQL statements.

Top comments (0)