C#读取SQLite数据库指定数据表内的一行数据
在C#中读取SQLite数据库指定数据表内的一行数据,你可以使用SQLiteDataReader类来执行查询并读取数据。下面是一个示例代码:
using System;
using System.Data.SQLite;
class Program
{
static void Main()
{
// 数据库连接字符串
string connectionString = "Data Source=database.db";
// SQL查询语句
string sql = "SELECT * FROM TableName WHERE Id = @Id";
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
{
connection.Open();
using (SQLiteCommand command = new SQLiteCommand(sql, connection))
{
// 设置查询参数
command.Parameters.AddWithValue("@Id", 1);
using (SQLiteDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
// 读取数据
int id = reader.GetInt32(0);
string name = reader.GetString(1);
Console.WriteLine("Id: {0}, Name: {1}", id, name);
}
else
{
Console.WriteLine("No data found.");
}
}
}
}
}
}
在上面的示例中,我们假设已经创建了一个名为TableName的数据表,并且该表包含Id和Name两个列。我们使用@Id参数来指定要查询的行的Id值。然后,我们使用GetInt32和GetString方法从查询结果中读取数据。如果查询结果为空,则输出"No data found."。
注意,为了使用SQLite数据库,你需要安装SQLite NuGet包。可以在Visual Studio中使用NuGet包管理器来安装SQLite NuGet包
原文地址: https://www.cveoy.top/t/topic/hL7F 著作权归作者所有。请勿转载和采集!