SQLite – Java

下面是一份 完整的 SQLite + Java 中文教程,涵盖从环境搭建到 CRUD 操作、事务、连接池等实用技巧,适合初学者和进阶开发者。


一、SQLite 简介

SQLite 是一个轻量级、嵌入式、零配置的数据库引擎,适合:

  • 桌面应用
  • 移动应用(Android)
  • 嵌入式系统
  • 本地数据存储

它将整个数据库保存在 单个文件 中,无需服务器。


二、添加 SQLite JDBC 驱动(Maven / Gradle)

Maven (pom.xml)

<dependency>
    <groupId>org.xerial</groupId>
    <artifactId>sqlite-jdbc</artifactId>
    <version>3.46.1</version>
</dependency>

Gradle (build.gradle)

implementation 'org.xerial:sqlite-jdbc:3.46.1'

手动下载 JAR:https://github.com/xerial/sqlite-jdbc


三、Java 连接 SQLite 数据库

import java.sql.*;

public class SQLiteDemo {
    private static final String DB_URL = "jdbc:sqlite:users.db";  // 数据库文件路径

    public static void main(String[] args) {
        try (Connection conn = DriverManager.getConnection(DB_URL)) {
            System.out.println("成功连接 SQLite 数据库!");
            创建表(conn);
            插入数据(conn, "张三", 28);
            插入数据(conn, "李四", 35);
            查询数据(conn);
        } catch (SQLException e) {
            System.err.println("数据库错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    // 创建 users 表
    private static void 创建表(Connection conn) throws SQLException {
        String sql = """
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                age INTEGER NOT NULL
            );
            """;
        try (Statement stmt = conn.createStatement()) {
            stmt.execute(sql);
            System.out.println("表 'users' 已创建或已存在。");
        }
    }

    // 插入数据
    private static void 插入数据(Connection conn, String name, int age) throws SQLException {
        String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
        try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setInt(2, age);
            pstmt.executeUpdate();
            System.out.println("已插入: " + name);
        }
    }

    // 查询数据
    private static void 查询数据(Connection conn) throws SQLException {
        String sql = "SELECT id, name, age FROM users ORDER BY age DESC";
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            System.out.println("\n--- 查询结果 ---");
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                System.out.printf("ID: %d | 姓名: %s | 年龄: %d%n", id, name, age);
            }
        }
    }
}

四、推荐使用 try-with-resources(自动关闭资源)

try (Connection conn = DriverManager.getConnection(DB_URL);
     PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE age > ?")) {

    pstmt.setInt(1, 25);
    try (ResultSet rs = pstmt.executeQuery()) {
        while (rs.next()) {
            System.out.println(rs.getString("name") + " - " + rs.getInt("age"));
        }
    }
} catch (SQLException e) {
    e.printStackTrace();
}

五、封装 CRUD 操作(UserDAO 类)

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDAO {
    private final String dbPath;

    public UserDAO(String dbPath) {
        this.dbPath = "jdbc:sqlite:" + dbPath;
        创建表();
    }

    private void 创建表() {
        String sql = """
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                age INTEGER NOT NULL
            );
            """;
        执行更新(sql);
    }

    // 增
    public void 插入(String name, int age) {
        String sql = "INSERT INTO users(name, age) VALUES(?, ?)";
        try (Connection conn = DriverManager.getConnection(dbPath);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setInt(2, age);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("插入失败", e);
        }
    }

    // 删
    public void 删除(int id) {
        String sql = "DELETE FROM users WHERE id = ?";
        try (Connection conn = DriverManager.getConnection(dbPath);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("删除失败", e);
        }
    }

    // 改
    public void 更新(int id, String name, int age) {
        String sql = "UPDATE users SET name = ?, age = ? WHERE id = ?";
        try (Connection conn = DriverManager.getConnection(dbPath);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, name);
            pstmt.setInt(2, age);
            pstmt.setInt(3, id);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新失败", e);
        }
    }

    // 查单个
    public User 查找(int id) {
        String sql = "SELECT * FROM users WHERE id = ?";
        try (Connection conn = DriverManager.getConnection(dbPath);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return new User(rs.getInt("id"), rs.getString("name"), rs.getInt("age"));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询失败", e);
        }
        return null;
    }

    // 查全部
    public List<User> 查找全部() {
        List<User> list = new ArrayList<>();
        String sql = "SELECT * FROM users";
        try (Connection conn = DriverManager.getConnection(dbPath);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                list.add(new User(rs.getInt("id"), rs.getString("name"), rs.getInt("age")));
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询全部失败", e);
        }
        return list;
    }

    private void 执行更新(String sql) {
        try (Connection conn = DriverManager.getConnection(dbPath);
             Statement stmt = conn.createStatement()) {
            stmt.execute(sql);
        } catch (SQLException e) {
            throw new RuntimeException("执行 SQL 失败: " + sql, e);
        }
    }
}

// User 实体类
class User {
    int id;
    String name;
    int age;

    public User(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{id=" + id + ", name='" + name + "', age=" + age + '}';
    }
}

六、事务支持(Transaction)

public void 转账示例(Connection conn, int fromId, int toId, int amount) throws SQLException {
    conn.setAutoCommit(false);  // 开启事务
    String deduct = "UPDATE accounts SET balance = balance - ? WHERE id = ?";
    String add = "UPDATE accounts SET balance = balance + ? WHERE id = ?";

    try (PreparedStatement ps1 = conn.prepareStatement(deduct);
         PreparedStatement ps2 = conn.prepareStatement(add)) {

        ps1.setInt(1, amount);
        ps1.setInt(2, fromId);
        ps1.executeUpdate();

        ps2.setInt(1, amount);
        ps2.setInt(2, toId);
        ps2.executeUpdate();

        conn.commit();  // 提交事务
        System.out.println("转账成功");
    } catch (SQLException e) {
        conn.rollback();  // 回滚
        System.out.println("转账失败,已回滚");
        throw e;
    } finally {
        conn.setAutoCommit(true);
    }
}

七、常见问题与最佳实践

问题解决方案
中文乱码SQLite 默认支持 UTF-8,确保数据库文件和 Java 字符串都是 UTF-8
数据库文件路径使用 new File("data.db").getAbsolutePath() 获取绝对路径
多线程安全每个线程使用独立 Connection,或使用连接池
性能优化使用 PRAGMA journal_mode = WAL; 提升并发性能
// 优化并发性能
try (Statement stmt = conn.createStatement()) {
    stmt.execute("PRAGMA journal_mode = WAL;");
    stmt.execute("PRAGMA synchronous = NORMAL;");
}

八、推荐工具

  • DB Browser for SQLite:图形化管理工具(类似 Navicat)
  • 下载:https://sqlitebrowser.org/
  • IntelliJ IDEA / Eclipse:集成 SQLite 插件

九、完整项目结构示例

src/
├── main/
│   ├── java/
│   │   ├── SQLiteDemo.java
│   │   ├── UserDAO.java
│   │   └── User.java
│   └── resources/
└── users.db        ← 自动生成

总结:SQLite + Java 组合非常适合轻量级本地应用开发,代码简单、部署方便、无需额外服务。

立即复制代码运行,你将拥有一个完整的 SQLite 数据库管理系统!

如需 Spring Boot + SQLiteAndroid 示例连接池(HikariCP),欢迎继续提问!

文章已创建 2326

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部