Home >Java >javaTutorial >How can I connect to and manipulate an SQLite database using Java?

How can I connect to and manipulate an SQLite database using Java?

DDD
DDDOriginal
2024-12-20 15:54:10597browse

How can I connect to and manipulate an SQLite database using Java?

Connecting SQLite with Java

Question:

How can Java be used to connect and manipulate an SQLite database?

Answer:

SQLite Java Connector Library

A popular connector library for interfacing Java with SQLite is the SQLite JDBC driver. This library allows Java applications to connect to SQLite databases using the JDBC (Java Database Connectivity) API. It can be added to a Java project by including the sqlitejdbc-v056.jar file in the classpath.

Example Usage

The following code snippet illustrates how to establish a connection, execute SQL commands, and retrieve data from an SQLite database using the SQLite JDBC driver:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class Test {
    public static void main(String[] args) throws Exception {
        Class.forName("org.sqlite.JDBC");
        Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
        Statement stat = conn.createStatement();
        stat.executeUpdate("drop table if exists people;");
        stat.executeUpdate("create table people (name, occupation);");
        PreparedStatement prep = conn.prepareStatement(
            "insert into people values (?, ?);");

        prep.setString(1, "Gandhi");
        prep.setString(2, "politics");
        prep.addBatch();
        prep.setString(1, "Turing");
        prep.setString(2, "computers");
        prep.addBatch();
        prep.setString(1, "Wittgenstein");
        prep.setString(2, "smartypants");
        prep.addBatch();

        conn.setAutoCommit(false);
        prep.executeBatch();
        conn.setAutoCommit(true);

        ResultSet rs = stat.executeQuery("select * from people;");
        while (rs.next()) {
            System.out.println("name = " + rs.getString("name"));
            System.out.println("job = " + rs.getString("occupation"));
        }
        rs.close();
        conn.close();
    }
}

This code demonstrates how to connect to the SQLite database test.db, create a people table, insert three records into it using batch processing, and finally retrieve and print the data from the table.

The above is the detailed content of How can I connect to and manipulate an SQLite database using Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn