Java 操作 sqlite 工具类
以下是一个简单的Java操作SQLite数据库的工具类示例。请确保你的项目中已经包含了SQLite JDBC驱动。
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SQLiteHelper {
private Connection connection;
public SQLiteHelper(String databaseFile) {
this.connect(databaseFile);
}
private void connect(String databaseFile) {
try {
// SQLite的JDBC URL
String url = "jdbc:sqlite:" + databaseFile;
connection = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void executeNonQuery(String sql, Object... params) {
try (PreparedStatement statement = connection.prepareStatement(sql)) {
for (int i = 0; i < params.length; i++) {
statement.setObject(i + 1, params[i]);
}
statement.executeUpdate();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public ResultSet executeQuery(String sql, Object... params) {
try (PreparedStatement statement = connection.prepareStatement(sql)) {
for (int i = 0; i < params.length; i++) {
statement.setObject(i + 1, params[i]);
}
return statement.executeQuery();
} catch (SQLException e) {
System.out.println(e.getMessage());
return null;
}
}
public void close() {
try {
if (connection != null && !connection.isClosed()) {
connection.close();
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
使用方法:
SQLiteHelper dbHelper = new SQLiteHelper("path_to_your_database.db");
try {
// 创建一个表
String createTableSQL = "CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)";
dbHelper.executeNonQuery(createTableSQL);
// 插入数据
String insertSQL = "INSERT INTO users (name, email) VALUES (?, ?)";
dbHelper.executeNonQuery(insertSQL, "Alice", "alice@examp
评论已关闭