最近在项目中遇到了一个问题,需要大量的间断性质的数据,直接上传会影响到效率。就想到了先本地保存,间隔固定时间汇总上传的方案。
以下是C#操作SQLite3数据库的完整实现方案,综合了连接、增删改查等核心功能:
using System;
using System.Data;
using System.Data.SQLite;
using System.IO;
public class SQLiteHelper
{
private static string connStr = "Data Source={0};Version=3;";
/// <summary>
/// 创建数据库文件
/// </summary>
public static void CreateDB(string filePath)
{
if (!File.Exists(filePath))
{
SQLiteConnection.CreateFile(filePath);
Console.WriteLine($"数据库已创建: {filePath}");
}
}
/// <summary>
/// 执行非查询SQL
/// </summary>
public static int ExecuteNonQuery(string sql, string dbPath)
{
using (var conn = new SQLiteConnection(string.Format(connStr, dbPath)))
{
conn.Open();
using (var cmd = new SQLiteCommand(sql, conn))
{
return cmd.ExecuteNonQuery();
}
}
}
/// <summary>
/// 查询数据
/// </summary>
public static DataTable ExecuteDataTable(string sql, string dbPath)
{
var dt = new DataTable();
using (var conn = new SQLiteConnection(string.Format(connStr, dbPath)))
{
conn.Open();
using (var adapter = new SQLiteDataAdapter(sql, conn))
{
adapter.Fill(dt);
}
}
return dt;
}
}
下边时简单应用案例
class Program
{
static void Main(string[] args)
{
string dbPath = "test.db";
// 创建数据库
SQLiteHelper.CreateDB(dbPath);
// 创建表
string createTableSql = @"CREATE TABLE IF NOT EXISTS Users (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT NOT NULL,
Age INTEGER)";
SQLiteHelper.ExecuteNonQuery(createTableSql, dbPath);
// 插入数据
string insertSql = "INSERT INTO Users (Name, Age) VALUES ('张三', 25)";
SQLiteHelper.ExecuteNonQuery(insertSql, dbPath);
// 查询数据
var dt = SQLiteHelper.ExecuteDataTable("SELECT * FROM Users", dbPath);
foreach (DataRow row in dt.Rows)
{
Console.WriteLine($"ID: {row["Id"]}, Name: {row["Name"]}, Age: {row["Age"]}");
}
}
}
代码功能说明:
SQLiteHelper类封装了数据库连接、创建、非查询执行和数据查询功能
1。采用参数化路径设计,支持动态指定数据库文件位置
2。实现了基本的CRUD操作,包括创建表、插入数据和查询显示
3。主程序展示了从创建数据库到查询数据的完整流程
4。使用前需通过NuGet安装System.Data.SQLite包,这是C#操作SQLite3的标准库
5。该实现采用了SQLite的无服务器特性,所有数据存储在单个.db文件中,适合本地应用程序使用
1078

被折叠的 条评论
为什么被折叠?



