news 2026/4/23 13:09:09

C#之安装和使用Sqlite数据库

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
C#之安装和使用Sqlite数据库

C#之安装和使用Sqlite数据库

Sqlite数据库使用流程

1.安装 System.Data.Sqlite1.0.1172.安装 sqlite.codefirst3.App.Config配置连接字符串5.配置<provider invariantName="System.Data.SQLite"type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6"/>3.创建ApplicationDbContext和User表实体

一 安装System.Data.Sqlite 1.0.117

二 安装 sqlite.codefirst

三 配置连接字符串

<connectionStrings><add name="SqliteDbContext"connectionString="data source=.\sqlite.db"providerName="System.Data.SQLite.EF6"/></connectionStrings>

<provider invariantName="System.Data.SQLite"type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6"/>

后续联系



四 创建User表实体

EntityBase

/// <summary>/// 实体类型/// </summary>public class EntityBase:ObservableObject{privateintid;/// <summary>/// 自增主键/// </summary>[Key][DatabaseGenerated(DatabaseGeneratedOption.Identity)]//自动递增publicintId{get=>id;set=>SetProperty(ref id,value);}private DateTime insertDate=DateTime.Now;/// <summary>/// 插入时间/// </summary>public DateTime InsertDate{get=>insertDate;set=>SetProperty(ref insertDate,value);}}

User

[Table(nameof(User))]public class User:EntityBase{private string userName;public string UserName{get=>userName;set=>SetProperty(ref userName,value);}private string password;public string Password{get=>password;set=>SetProperty(ref password,value);}privateintrole;publicintRole{get=>role;set=>SetProperty(ref role,value);}}

User表的增删改查的接口设计

IRepository

where T:class 约束为类
public interface IRepository<T>where T:class{TGet(intid);intUpdate(T entity);intDelete(T entity);intInsert(T entity);List<T>GetAll();List<T>GetAll(string keyword);TSelect(string keyword);}

IUserRepository

public interface IUserRepository:IRepository<User>{}

增删改查实现

SqliteDbContext

public class SqliteDbContext:DbContext{//读取配置文件connectionStrings,创建数据库映射publicSqliteDbContext():base("SqliteDbContext"){}public DbSet<User>Users{get;set;}protected overridevoidOnModelCreating(DbModelBuilder modelBuilder){//base.OnModelCreating(modelBuilder);//注入我们设置的SqliteDbContext,判断数据库是否存在?不存在则创建。var sqliteConnect=new SqliteCreateDatabaseIfNotExists<SqliteDbContext>(modelBuilder);//执行Database.SetInitializer(sqliteConnect);}}

RepositoryBase

public abstract class RepositoryBase{protectedstaticSqliteDbContext db{get;}=new Lazy<SqliteDbContext>().Value;}

UserRepository

public class UserRepository:RepositoryBase,IUserRepository{publicintDelete(User entity){db.Entry(entity).State=System.Data.Entity.EntityState.Deleted;returndb.SaveChanges();}public UserGet(intid){returndb.Users.Find(id);}public List<User>GetAll(){returndb.Users.ToList();}public List<User>GetAll(string keyword){returndb.Users.ToList().Where(t=>t.UserName.Contains(keyword)).ToList();}publicintInsert(User entity){db.Users.Add(entity);returndb.SaveChanges();}public UserSelect(string keyword){returndb.Users.ToList().Find(t=>t.UserName==keyword);}publicintUpdate(User entity){db.Entry(entity).State=System.Data.Entity.EntityState.Modified;returndb.SaveChanges();}}

使用

publicMainWindow(){InitializeComponent();}UserRepository xx=newUserRepository();privatevoidButton_Click(object sender,RoutedEventArgs e){User newUser=newUser();newUser.UserName="admin";newUser.Password="12345678";newUser.InsertDate=DateTime.Now;intcount=xx.Insert(newUser);if(count>0){System.Windows.MessageBox.Show("插入成功");}var entity=xx.GetAll().FirstOrDefault();}

补充:

在WinForms开发中安装System.Data.SQLitesqlite.codefirstEntityFramework这三个库,各自承担不同的功能角色,以下是具体用途及分析:

1. System.Data.SQLite

核心作用:提供与SQLite数据库交互的底层ADO.NET接口。
功能细节

  • 原生SQLite支持:作为官方维护的库,直接封装SQLite的C语言接口,提供连接、命令执行、数据读取等基础操作。
  • 跨平台兼容性:支持Windows、Linux、macOS等平台,适合需要跨平台部署的WinForms应用。
  • 性能优化:针对SQLite特性优化,如内存管理、事务处理等,适合高频读写场景。
  • 独立使用:无需依赖其他ORM框架,可直接通过SQLiteConnectionSQLiteCommand等类操作数据库。

适用场景

  • 需要直接控制SQL语句执行的场景(如复杂查询、存储过程)。
  • 对性能要求较高,或需避免ORM框架开销的项目。
  • 跨平台WinForms应用开发。

示例代码

usingSystem.Data.SQLite;// 连接数据库using(varconnection=newSQLiteConnection("Data Source=mydb.sqlite")){connection.Open();// 执行SQL命令using(varcommand=newSQLiteCommand("SELECT * FROM Users",connection))using(varreader=command.ExecuteReader()){while(reader.Read()){Console.WriteLine(reader["Name"]);}}}

2. sqlite.codefirst

核心作用:通过Code First模式自动生成SQLite数据库表结构。
功能细节

  • Code First支持:允许开发者通过定义C#类(实体)自动创建或更新数据库表,无需手动编写SQL脚本。
  • 迁移管理:支持数据库迁移,可跟踪模型变化并自动应用变更到数据库。
  • 依赖EntityFramework:本质上是EntityFramework的扩展,需配合EF使用。

适用场景

  • 快速原型开发,需快速迭代数据库结构。
  • 团队熟悉EF的Code First模式,希望减少手动维护SQL脚本的工作量。
  • 需要与EntityFramework无缝集成的项目。

示例代码(需先安装EntityFramework):

// 定义实体类publicclassUser{publicintId{get;set;}publicstringName{get;set;}}// 配置DbContextpublicclassMyDbContext:DbContext{publicDbSet<User>Users{get;set;}protectedoverridevoidOnConfiguring(DbContextOptionsBuilderoptionsBuilder){optionsBuilder.UseSqlite("Data Source=mydb.sqlite");}}// 自动生成数据库using(varcontext=newMyDbContext()){context.Database.EnsureCreated();// 若数据库不存在则创建}

3. EntityFramework (EF)

核心作用:提供高级ORM(对象关系映射)功能,简化数据访问层开发。
功能细节

  • LINQ支持:通过LINQ查询语法直接操作数据库,无需编写SQL。
  • 变更跟踪:自动跟踪实体状态(新增、修改、删除),简化数据同步。
  • 延迟加载:支持按需加载关联数据,减少不必要的查询。
  • 多数据库支持:通过提供程序(如Microsoft.EntityFrameworkCore.Sqlite)支持多种数据库。

适用场景

  • 需要快速开发数据驱动型WinForms应用。
  • 团队熟悉EF,希望减少样板代码(如手动映射对象与表)。
  • 需要复杂查询或关联数据操作的场景。

示例代码(结合Microsoft.EntityFrameworkCore.Sqlite):

// 查询数据using(varcontext=newMyDbContext()){varusers=context.Users.Where(u=>u.Name.Contains("A")).ToList();foreach(varuserinusers){Console.WriteLine(user.Name);}}

三者的关系与选择建议

  • System.Data.SQLite:底层驱动,必选(若直接操作SQLite)。
  • EntityFramework:高层ORM,可选(若需简化数据访问)。
  • sqlite.codefirst:EF的扩展,可选(若需Code First模式)。

推荐组合

  • 基础场景System.Data.SQLite(直接操作数据库)。
  • 快速开发System.Data.SQLite+EntityFramework(ORM简化代码)。
  • 敏捷迭代System.Data.SQLite+EntityFramework+sqlite.codefirst(Code First自动管理表结构)。

注意事项

  • 若项目已使用EF Core,建议通过Microsoft.EntityFrameworkCore.Sqlite(而非System.Data.SQLite)作为提供程序,以避免冲突。
  • sqlite.codefirst非官方库,需评估其稳定性与维护性。

EF6

EF6(Entity Framework 6) 是 Microsoft 提供的 对象关系映射(ORM)框架,用于简化 .NET 应用程序与数据库的交互。它通过将数据库表映射为 C#/VB.NET 对象,使开发者能以面向对象的方式操作数据,而无需直接编写 SQL 语句。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/11 7:27:14

唯一屹立的厂商: Elastic 在 2025 AV-Comparatives 测试中的全面胜出

作者&#xff1a;来自 Elastic Roxana Gheorghe 标题在当前的威胁环境中&#xff0c;几乎没有犯错的余地。根据 IBM Cost of a Data Breach Report 2025 【1】&#xff0c; 美国数据泄露的平均成本已飙升至创纪录的 1022 万美元 — 比上一年增长 9%。对安全团队来说&#xff0c…

作者头像 李华
网站建设 2026/4/19 20:31:53

串口通信基础知识

一、串行通讯与并行通讯在通信和计算机科学中&#xff0c;串行通信(Serial Communication)是一个通用概念&#xff0c;泛指所有的串行的通信协议&#xff0c;如RS232、RS422、RS485、USB、I2C、SPI等。串行通讯是指仅用一根接收线和一根发送线就能将数据以位进行传输的一种通讯…

作者头像 李华
网站建设 2026/4/23 1:44:01

ADP2108AUJZ-2.5-R7,峰值效率可达95%的600mA降压转换器, 现货库存

型号介绍今天我要向大家介绍的是 Analog Devices 的一款转换器——ADP2108AUJZ-2.5-R7。 它可以将输入的直流电压&#xff08;比如来自电池或电源适配器的电压&#xff09;转换成更低的直流电压&#xff0c;并输出稳定的电流。当设备需要更多或更少的电流时&#xff0c;它能够快…

作者头像 李华
网站建设 2026/4/19 22:15:34

Volatility 入门常用命令清单

注&#xff1a;命令基本格式为 volatility -f [内存镜像文件] --profile[系统配置文件] [插件命令] &#xff0c; profile 需匹配镜像的系统版本&#xff08;如 Win7SP1x64 &#xff09;一、 基础信息识别1. imageinfo作用&#xff1a;分析内存镜像&#xff0c;推荐适配的 …

作者头像 李华
网站建设 2026/4/18 10:57:50

单目实时3D识别

LeAD-M3D: Leveraging Asymmetric Distillation for Real-time Monocular 3D Detection

作者头像 李华