java如何使用sqlite
使用 Java 连接 SQLite 数据库
确保项目中包含 SQLite JDBC 驱动。可以通过 Maven 添加依赖:
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.40.0.0</version>
</dependency>
创建数据库连接
使用 DriverManager.getConnection 建立连接,SQLite 的 JDBC URL 格式为 jdbc:sqlite:path/to/database.db:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class SQLiteDemo {
public static void main(String[] args) {
Connection conn = null;
try {
// 创建或连接到数据库文件
conn = DriverManager.getConnection("jdbc:sqlite:sample.db");
System.out.println("Connection to SQLite established.");
} catch (SQLException e) {
System.err.println(e.getMessage());
} finally {
try {
if (conn != null) conn.close();
} catch (SQLException e) {
System.err.println(e.getMessage());
}
}
}
}
执行 SQL 语句
通过 Statement 或 PreparedStatement 执行 SQL 操作。以下示例创建表并插入数据:
Statement stmt = conn.createStatement();
stmt.execute("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)");
// 使用 PreparedStatement 防止 SQL 注入
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO users (name, email) VALUES (?, ?)");
pstmt.setString(1, "Alice");
pstmt.setString(2, "alice@example.com");
pstmt.executeUpdate();
查询数据
使用 ResultSet 处理查询结果:

ResultSet rs = stmt.executeQuery("SELECT * FROM users");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}
rs.close();
事务处理
通过 setAutoCommit(false) 启用事务,完成后调用 commit():
conn.setAutoCommit(false);
try {
// 执行多个 SQL 操作
conn.commit();
} catch (SQLException e) {
conn.rollback();
System.err.println("Transaction failed: " + e.getMessage());
} finally {
conn.setAutoCommit(true);
}
关闭资源
确保关闭所有数据库资源以避免内存泄漏:
if (stmt != null) stmt.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
注意事项
SQLite 适合嵌入式和小型应用,不支持多用户高并发场景。对于复杂查询,建议使用索引优化性能。JDBC 驱动会自动创建不存在的数据库文件,但需确保应用有文件系统的写入权限。






