C#基于SQLiteHelper类实现存取SQLite数据库的方法
using System;
using System.Data;
using System.Data.SQLite;
public class SQLiteHelper
{
private string connectionString;
public SQLiteHelper(string databaseFile)
{
connectionString = $"Data Source={databaseFile}";
}
public int ExecuteNonQuery(string query)
{
using (var connection = new SQLiteConnection(connectionString))
{
using (var command = new SQLiteCommand(query, connection))
{
connection.Open();
return command.ExecuteNonQuery();
}
}
}
public DataTable ExecuteQuery(string query)
{
using (var connection = new SQLiteConnection(connectionString))
{
using (var command = new SQLiteCommand(query, connection))
{
using (var dataAdapter = new SQLiteDataAdapter(command))
{
var dataTable = new DataTable();
connection.Open();
dataAdapter.Fill(dataTable);
return dataTable;
}
}
}
}
}
// 使用示例
var helper = new SQLiteHelper("path_to_your_database.db");
// 执行非查询命令
int rowsAffected = helper.ExecuteNonQuery("INSERT INTO TableName (Column1, Column2) VALUES (Value1, Value2)");
// 执行查询命令
DataTable table = helper.ExecuteQuery("SELECT * FROM TableName");
这段代码提供了一个基于SQLite的SQLiteHelper
类,它封装了打开数据库连接、执行命令和处理结果集的常见操作。使用using
语句确保了资源的正确释放。这是一个简洁且有效的实现,可以作为开发者在处理SQLite数据库操作时的参考。
评论已关闭