Write data to SQLite using Java

o write data to a SQLite database using Java, you can use the JDBC driver provided by the SQLite project. Here’s an example code snippet that demonstrates how to write data to a SQLite database using Java:

import java.sql.*;

public class SQLiteDataWriter {
    public static void main(String[] args) {
        // Database URL
        String url = "jdbc:sqlite:/path/to/your/database.sqlite";

        // SQL query
        String query = "INSERT INTO your_table (name, email) VALUES (?, ?)";

        try {
            // Register JDBC driver
            Class.forName("org.sqlite.JDBC");

            // Open a connection
            Connection conn = DriverManager.getConnection(url);

            // Create a prepared statement
            PreparedStatement stmt = conn.prepareStatement(query);

            // Set parameter values
            stmt.setString(1, "John Doe");
            stmt.setString(2, "[email protected]");

            // Execute the query
            int rowsAffected = stmt.executeUpdate();

            // Process the result
            System.out.println(rowsAffected + " row(s) inserted successfully.");

            // Close the resources
            stmt.close();
            conn.close();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

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

Make sure to have the SQLite JDBC driver (e.g., sqlite-jdbc-*.jar) included in your classpath. You can download the driver from the official SQLite website or include it as a Maven/Gradle dependency.

The code connects to the SQLite database, creates a prepared statement, sets the parameter values using setString(), and executes the insert query using executeUpdate(). The method returns the number of rows affected, which can be used for result processing. Finally, it closes the resources to free up memory.

Remember to handle exceptions appropriately in your production code and consider using try-with-resources or a similar mechanism to automatically close the resources.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech