C# 连接 SQLite 数据库:完整指南及代码示例
以下是使用 C# 连接 SQLite 数据库的示例代码:
- 引用 SQLite 库
在 Visual Studio 中,右键单击项目,选择'管理 NuGet 程序包',搜索并安装 System.Data.SQLite.Core 库。
- 创建 SQLite 连接对象
使用 SQLiteConnection 类创建 SQLite 连接对象,并设置连接字符串:
using System.Data.SQLite;
SQLiteConnection conn = new SQLiteConnection('Data Source=database.sqlite;Version=3;');
其中,Data Source 指定数据库文件路径,Version 指定 SQLite 版本号。
- 打开连接
使用 Open 方法打开连接:
conn.Open();
- 执行 SQL 语句
使用 SQLiteCommand 类创建 SQLite 命令对象,并执行 SQL 语句:
SQLiteCommand cmd = new SQLiteCommand('SELECT * FROM table', conn);
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// 处理查询结果
}
其中,SELECT * FROM table 是 SQL 查询语句,SQLiteDataReader 类用于读取查询结果。
- 关闭连接
使用 Close 方法关闭连接:
conn.Close();
完整示例代码:
using System.Data.SQLite;
SQLiteConnection conn = new SQLiteConnection('Data Source=database.sqlite;Version=3;');
conn.Open();
SQLiteCommand cmd = new SQLiteCommand('SELECT * FROM table', conn);
SQLiteDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// 处理查询结果
}
conn.Close();
原文地址: https://www.cveoy.top/t/topic/jKxO 著作权归作者所有。请勿转载和采集!