当前位置: 首页 > article >正文

C#与Sqlite数据库

1,一般的访问方式。

1.1,连接语句。
//sqlite 连接,支持相对位置,也支持绝对位置
Data Source=../../Database/cater.db

// 连接数据库,FailIfMissing=false时若文件不存在会自动创建
string connStr ="DataSource=test.db;Version=3;Pooling=true;FailIfMissing=false;";
1.2,配置文件设置。
//需在配置文件中进行如下配置否则报错
<startup useLegacyV2RuntimeActivationPolicy="true"> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
 1.3,常用语法。
//语法:
select * from AlarmHistory
insert into alarmhistory (AlarmDetails,starttime) values ('abc',getdate())
//获取当前时间
select datetime('now')
SELECT datetime('now', 'localtime');
select CURRENT_TIMESTAMP

//插入当前时间
insert into alarmhistory (alarmdetails,starttime) values('',datetime('now','localtime'))

//查找为null的数据
select * from alarmhistory where StartTime is null

//修改表格序号
 update sqlite_sequence set seq = 0 where name = 'AlarmHistory'

//查询表格主键
select * from
pragma_table_info ('ActualData') where pk=1

//查询表格是否存在
select exists(  select * from sqlite_master where type='table' and name='ActualData')

//删除表格
 drop table 'ActualData' 

//获取和设置时间,时间格式只支持类似yyyy-MM-dd这样用-连接的格式,若用/连接则无效
select datetime('2024-08-22 16:23:55')
SELECT datetime('now', 'localtime');
1.4,SQLite访问dll。

https://download.csdn.net/download/lingxiao16888/89914696

2,基于EntityFramework的ORM数据访问。

2.1,安装Nuget包

这部分比较简单,直接Nuget包中下载即可

  1. System.Data.SQLite
  2. System.Data.SQLite.EF6
  3. System.Data.SQLite.LINQ
  4. SQLite.CodeFirst

2.2,配置文件需要进行如下修改。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
	<configSections>
		<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
		<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
	</configSections>
	<startup>
		<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
	</startup>
	<entityFramework>
		<providers>
			<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
			<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
			<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
		</providers>
	</entityFramework>
	<system.data>
		<DbProviderFactories>
			<remove invariant="System.Data.SQLite.EF6" />
			<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
			<remove invariant="System.Data.SQLite" />
			<add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" />
		</DbProviderFactories>
	</system.data>
</configuration>
2.3,应用。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            MyDbContext context = new MyDbContext("cater.db");
            var set = context.Set<MemmberType>();
            var ss = set.FirstOrDefault();
            foreach (var item in set)
            {
                Console.WriteLine($"{item.MemTpName} ; {item.MemType} ; {item.MemTpDesc} ; {item.SubBy} ;{item.DelFlag}");
            }
            
            Console.WriteLine("输出完成!");
            Console.ReadKey();
        }
    }
    class MyDbContext : DbContext
    {
        public MyDbContext(string constr) : base(new SQLiteConnection
        {
            ConnectionString = new SQLiteConnectionStringBuilder
            {
                DataSource = constr,
                ForeignKeys = true
            }.ConnectionString

        }
            , true)
        {

        }
        //如果查询 MemmberType 表,则该属性不能省略
        public virtual DbSet<MemmberType>  MemmberType { get; set; }

    }

    [Table("MemmberType")]//该特性不能省略
    class MemmberType
    {
        [Key]//如果存在主键该特性不能省略
        [Column("MemType",TypeName ="INT")]
        public int MemType { get; set; }
        //[Column("MemTpName")]
        public string MemTpName { get; set; }
        [Column("MemTpDesc")]//可使用 Required 特性指定该列不能为空
        public string MemTpDesc { get; set; }
        //[Column("DelFlag")]
        public int DelFlag { get; set; }
        //[Column("SubBy")]
        public int SubBy { get; set; }
    }
}
2.4,效果。

数据库文件数据。

查询结果。


http://www.kler.cn/news/365924.html

相关文章:

  • 【Unity 安装教程】
  • 【2024|滑坡数据集论文解读1】CAS滑坡数据集:用于深度学习滑坡检测的大规模多传感器数据集
  • 【WebGis开发 - Cesium】三维可视化项目教程---图层管理拓展图层顺序调整功能
  • java中使用redis的方法
  • CSS行块标签的显示方式
  • webView 支持全屏播放
  • 01. 初识C++
  • 钉钉录播抓取视频
  • UML 总结(基于《标准建模语言UML教程》)
  • HW支持-定时扫描局域网内所有设备MAC不在白名单则邮件提醒
  • winmm劫持详解
  • postman使用——在公司的项目落地回顾总结
  • 【计算机操作系统】课程 作业二 进程与线程 408考研
  • uniapp使用easyinput文本框显示输入的字数和限制的字数
  • WUP-MY-POS-PRINTER 旻佑热敏打印机票据打印uniapp插件使用说明
  • WebGL 3D基础
  • 常见Linux命令笔记
  • 【python爬虫】request发请求时需要携带cookies请求举例
  • 计算机网络:网络层 —— IPv4 协议的表示方法及其编址方法
  • 定位基站共线
  • 【卡尔曼滤波】观测模型包含输入的线性卡尔曼滤波
  • C++的汉诺塔
  • 【C语言教程】【嵌入式编程】(五)驱动开发实战(六)高级实践项目(七)附录
  • 10分钟使用Strapi(无头CMS)生成基于Node.js的API接口,告别繁琐开发,保姆级教程,持续更新中。
  • uniapp写移动端,适配苹果手机底部导航栏,ios安全区问题,苹果手机遮挡底部信息,uview的u-action-sheet组件
  • Go语言基础教程:递归