C# SQLite 数据库连接教程:完整步骤和代码示例
在 C# 中连接 SQLite 数据库,需要使用 SQLite.Net 库。以下是连接 SQLite 数据库的基本步骤:
- 安装 SQLite.Net 库
可以通过 NuGet 包管理器安装 SQLite.Net-PCL 或 SQLite.Net.Async-PCL。这两个库都支持异步操作,区别在于 SQLite.Net.Async-PCL 支持异步操作。
- 创建 SQLite 连接对象
使用 SQLiteConnection 类创建 SQLite 连接对象。SQLiteConnection 构造函数需要传递数据库文件路径作为参数。
string dbPath = 'database.db';
SQLiteConnection connection = new SQLiteConnection(dbPath);
- 创建数据表
使用 SQLiteConnection.CreateTable
connection.CreateTable<Person>();
- 插入数据
使用 SQLiteConnection.Insert() 方法插入数据。需要传递实体对象作为参数。
Person person = new Person { Name = 'Tom', Age = 20 };
connection.Insert(person);
- 查询数据
使用 SQLiteConnection.Table
IEnumerable<Person> persons = connection.Table<Person>();
foreach (Person person in persons)
{
Console.WriteLine(person.Name + ' ' + person.Age);
}
- 更新数据
使用 SQLiteConnection.Update() 方法更新数据。需要传递实体对象作为参数。
Person person = connection.Table<Person>().FirstOrDefault(p => p.Name == 'Tom');
if (person != null)
{
person.Age = 30;
connection.Update(person);
}
- 删除数据
使用 SQLiteConnection.Delete() 方法删除数据。需要传递实体对象作为参数。
Person person = connection.Table<Person>().FirstOrDefault(p => p.Name == 'Tom');
if (person != null)
{
connection.Delete(person);
}
完整代码示例:
using System;
using System.Collections.Generic;
using SQLite.Net;
using SQLite.Net.Attributes;
using SQLite.Net.Platform.Win32;
namespace SQLiteDemo
{
class Program
{
static void Main(string[] args)
{
string dbPath = 'database.db';
SQLiteConnection connection = new SQLiteConnection(new SQLitePlatformWin32(), dbPath);
connection.CreateTable<Person>();
Person person1 = new Person { Name = 'Tom', Age = 20 };
Person person2 = new Person { Name = 'Jerry', Age = 25 };
connection.Insert(person1);
connection.Insert(person2);
IEnumerable<Person> persons = connection.Table<Person>();
foreach (Person person in persons)
{
Console.WriteLine(person.Name + ' ' + person.Age);
}
Person personToUpdate = connection.Table<Person>().FirstOrDefault(p => p.Name == 'Tom');
if (personToUpdate != null)
{
personToUpdate.Age = 30;
connection.Update(personToUpdate);
}
Person personToDelete = connection.Table<Person>().FirstOrDefault(p => p.Name == 'Jerry');
if (personToDelete != null)
{
connection.Delete(personToDelete);
}
Console.ReadLine();
}
}
public class Person
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
}
原文地址: https://www.cveoy.top/t/topic/jKxJ 著作权归作者所有。请勿转载和采集!