news 2026/7/28 0:22:36

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/7/27 20:51:53

活动力度大的门头招牌企业

活动力度大的门头招牌企业在商业竞争日益激烈的今天&#xff0c;一个独特且吸引人的门头招牌对于企业的重要性不言而喻。而在众多门头招牌企业中&#xff0c;活动力度大的企业往往更受客户青睐。以贰师兄广告为例&#xff0c;它就是这样一家值得关注的企业。活动丰富&#xff0…

作者头像 李华
网站建设 2026/7/28 2:37:30

Java毕设选题推荐:基于JavaWeb的兽医站管理系统的设计与实现现代化兽医站管理系统【附源码、mysql、文档、调试+代码讲解+全bao等】

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

作者头像 李华
网站建设 2026/7/26 15:57:46

Arduino配置8266开发板

arduino ide下载网址&#xff1a; https://www.arduino.cc/en/software/ 首选项中配置ESP8266开发板地址&#xff1a; https://dl.espressif.com/dl/package_esp32_index.json http://arduino.esp8266.com/stable/package_esp8266com_index.json 开发板管理中搜索ESP8266后安…

作者头像 李华
网站建设 2026/7/24 16:54:58

【课程设计/毕业设计】基于SpringBoot+Vue茶叶销售系统的设计与实现基于Java语言的茶叶销售系统的前端设计与实现【附源码、数据库、万字文档】

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

作者头像 李华
网站建设 2026/7/27 4:11:19

41. 缺失的第一个正数

41. 缺失的第一个正数 困难 给你一个未排序的整数数组 nums &#xff0c;请你找出其中没有出现的最小的正整数。 请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。 示例 1&#xff1a; 输入&#xff1a;nums [1,2,0] 输出&#xff1a;3 解释&#xff1a…

作者头像 李华