C#Sqlite数据库操作介绍以及类库介绍
在C#中操作SQLite数据库,通常使用System.Data.SQLite
这个类库。以下是如何使用System.Data.SQLite
进行基本的数据库操作的例子:
首先,确保已经安装System.Data.SQLite
。可以通过NuGet安装:
Install-Package System.Data.SQLite
下面是一个简单的示例,展示了如何使用System.Data.SQLite
执行基本的数据库操作:
using System;
using System.Data.SQLite;
namespace SQLiteExample
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=example.db;Version=3;";
using (var connection = new SQLiteConnection(connectionString))
{
connection.Open();
// 创建一个表
using (var command = new SQLiteCommand(connection))
{
command.CommandText = "CREATE TABLE IF NOT EXISTS People (Id INTEGER PRIMARY KEY, Name TEXT, Age INTEGER);";
command.ExecuteNonQuery();
}
// 插入数据
using (var insertCommand = new SQLiteCommand(connection))
{
insertCommand.CommandText = "INSERT INTO People (Name, Age) VALUES ('Alice', 30);";
insertCommand.ExecuteNonQuery();
}
// 查询数据
using (var queryCommand = new SQLiteCommand(connection))
{
queryCommand.CommandText = "SELECT * FROM People;";
using (var reader = queryCommand.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine($"Id: {reader["Id"]}, Name: {reader["Name"]}, Age: {reader["Age"]}");
}
}
}
// 更新数据
using (var updateCommand = new SQLiteCommand(connection))
{
updateCommand.CommandText = "UPDATE People SET Age = Age + 1 WHERE Name = 'Alice';";
updateCommand.ExecuteNonQuery();
}
// 删除数据
using (var deleteCommand = new SQLiteCommand(connection))
{
deleteCommand.CommandText = "DELETE FROM People WHERE Name = '
评论已关闭