news 2026/3/11 13:28:54

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/3/9 1:27:39

大模型学习笔记

公司私有数据大模型应用方案1. RAG&#xff08;Retrieval Augmented Generation&#xff09;1&#xff09;工作原理RAG 通过从外部知识库中检索相关信息&#xff0c;并将其作为提示输入给大型语言模型&#xff08;LLMs&#xff09;&#xff0c;以增强模型处理知识密集型任务的能…

作者头像 李华
网站建设 2026/3/11 7:50:49

Windows Subsystem for Linux (WSL) 介绍

&#x1f4bb; Windows Subsystem for Linux (WSL) 介绍 WSL&#xff08;适用于 Linux 的 Windows 子系统&#xff09;是微软开发的一项 Windows 功能&#xff0c;它允许开发人员直接在 Windows 操作系统上运行完整的 GNU/Linux 环境&#xff0c;包括大多数命令行工具、实用程序…

作者头像 李华
网站建设 2026/3/11 12:55:55

sward全面介绍(13) - 集成Ldap,使用Ldap用户登录sward

集成ldap用户功能划入社区版本&#xff0c;本篇文章将全面介绍如何在sward中集成ldap用户并实现ldap用户登录sward。1、配置Ldap进入系统设置->用户->用户目录&#xff0c;点击Ldap后的配置按钮&#xff0c;填写Ldap的配置信息。参数说明类型选择Ldap服务器类型AD/LDAP名…

作者头像 李华
网站建设 2026/3/4 9:48:41

高效RANSAC

GitHub - ShiPC-AI/TCF: [RAL 2024] RANSAC Back to SOTA: A Two-Stage Consensus Filtering for Real-Time 3D Registration

作者头像 李华
网站建设 2026/3/4 19:23:19

建造者模式-创建型

一、建造者模式 1.1、核心思想 将一个复杂对象的构建与它的表示分离&#xff0c;使得同样的构建过程可以创建不同的表示。<>&#xff08;说人话&#xff09;创建步骤复杂&#xff0c;需要过多参数&#xff0c;用户只提供自己的参数&#xff0c;只关心最后的结果&#xff…

作者头像 李华
网站建设 2026/3/3 14:42:34

Java毕设选题推荐:基于Javaweb的二手儿童绘本交易系统设计与实现少儿图书循环共享租赁系统【附源码、mysql、文档、调试+代码讲解+全bao等】

博主介绍&#xff1a;✌️码农一枚 &#xff0c;专注于大学生项目实战开发、讲解和毕业&#x1f6a2;文撰写修改等。全栈领域优质创作者&#xff0c;博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围&#xff1a;&am…

作者头像 李华