0

0

C# Sqlite 本地存储的详情介绍

黄舟

黄舟

发布时间:2017-02-28 11:32:08

|

1728人浏览过

|

来源于php中文网

原创

1. download sqlite dll from:

http://www.sqlite.org/download.html

windows 版本:

http://www.sqlite.org/2016/sqlite-dll-win32-x86-3130000.zip

2. 拷贝 sqlite3.dll 到 bin 目录

3. 安装nuget: Install-Package sqlite-net
安装后会在项目中找到SQLite.CS和SQLiteAsync.cs
4. demo 代码:
4.1 创建一个抽象的base model :

public abstract class BaseModel
    {
        [PrimaryKey]
        public Guid Id { get; set; }


        protected BaseModel()
        {
            Id = Guid.NewGuid();
        }
    }

4.2 测试model

品牌空间(brand)
品牌空间(brand)

品牌空间为站长提供本地商家的网上展示系统,它具有丰富的功能,如商品、相册、消费券、团购、公告等。 品牌空间基于 UCenter,能够独立建站。 品牌空间(brand) v2.1 UTF-8 重点更新:A 增加商品0元支付预订功能B 增加店铺商品分类标签功能C 增加全站地图频道D 增加新的店铺通栏模板E 增加店铺认证功能F 增加商情聚合频道G 增加店铺首页橱窗图片轮播功能H 增加店铺首页商家介绍区

下载
 public class Book : BaseModel
    {
        public Book()
        {
            
        }
        public Book(string title, string author, int pages)
            :base()
        {
            Title = title;
            Author = author;
            Pages = pages;
        }
        public string Title { get; set; }


        public int Pages { get; set; }


        public string Author { get; set; }


        public override string ToString()
        {
            return string.Format("ID : {0} ,title : {1}, Author : {2}, Pages : {3}", Id, Title, Author, Pages);
        }
    }

4.3 创建helper class

public class SqliteHelper
    {
        private const string DBPath = "Book.db";
        private const int OPERATION_SUCCESS = 1;


        public static bool TryDropTable()
        {
            using (var db = new SQLite.SQLiteConnection(DBPath))
            {
                var success = db.DropTable();
                if (success != OPERATION_SUCCESS)
                {
                    // TODO log error
                }


                return success == OPERATION_SUCCESS;
            }
        }


        public static bool TryCreateTable()
        {
            using (var db = new SQLite.SQLiteConnection(DBPath))
            {
                var table = db.GetTableInfo(typeof (T).Name);
                if(table != null && table.Count > 0)
                {
                    return false;
                }
                db.CreateTable();
                return true;
            }
        }


        public static T Add(T book)
        {
            using (var db = new SQLite.SQLiteConnection(DBPath))
            {
                var success = db.Insert(book);
                if (success != OPERATION_SUCCESS)
                {
                    //TODO error log
                }
            }
            return book;
        }


        public static T DeleteById(Guid id) where T : BaseModel, new()
        {
            using (var db = new SQLite.SQLiteConnection(DBPath))
            {
                var record = db.Table().FirstOrDefault(x => x.Id == id);
                if (record != null)
                {
                    var success = db.Delete(record);
                    if (success != OPERATION_SUCCESS)
                    {
                        // TODO error log
                        return null;
                    }
                    return record;
                }
                else
                {
                    // TODO log : failed to find record with id 'XXX'
                    return null;
                }
            }
        }


        public static T UpdateById(Guid id, T updating) where T: BaseModel, new ()
        {
            using (var db = new SQLite.SQLiteConnection(DBPath))
            {
                var singleRecord = db.Table().FirstOrDefault(x => x.Id == id);
                if (singleRecord != null)
                {
                    singleRecord = updating;
                    singleRecord.Id = id; //restore the id


                    var success = db.Update(singleRecord);
                    if (success != OPERATION_SUCCESS)
                    {
                        // TODO error log
                        return null;
                    }
                    return updating;
                }
                else
                {
                    // TODO log  failed to find record with id 'XXX'
                    return null;
                }
            }
        }


        public static T UpdateBy(Expression> where, T updating) where T:BaseModel, new ()
        {
            using (var db = new SQLite.SQLiteConnection(DBPath))
            {
                var records = db.Table().Where(where).ToList();
                if (records.Count > 0)
                {
                    for (int i = 0; i < records.Count; i++)
                    {
                        var id = records[i].Id;
                        records[i] = updating;
                        records[i].Id = id; // restore id
                    }
                    var success = db.UpdateAll(records);
                    if (success != OPERATION_SUCCESS)
                    {
                        //TODO error log here
                        return null;
                    }
                    return updating;
                }
                return null;
            }
        }


        public static IEnumerable All() where T: new()
        {
            using (var db = new SQLite.SQLiteConnection(DBPath))
            {
                return db.Table().ToList();
            }
        }


        public static IEnumerable GetBy(Expression> prediction) where T: new()
        {
            using (var db = new SQLite.SQLiteConnection(DBPath))
            {
                return Enumerable.ToList(db.Table().Where(prediction));
            }
        }
    }

5. 使用过程

class Program
    {
        static void Main(string[] args)
        {
            SqliteHelper.TryDropTable();


            // create a table
            var createResult = SqliteHelper.TryCreateTable();
            Console.WriteLine("First time creating table 'Book' result : " +createResult);


            // try create it again
            createResult = SqliteHelper.TryCreateTable();
            Console.WriteLine("2nd time creating table 'Book' result : " + createResult);


            // try add record
            var firstRecord = SqliteHelper.Add(new Book("first", "aaa", 100));
            Console.WriteLine("first book added :");
            Console.WriteLine(firstRecord);
            // try update by id
            var updatedFirst = SqliteHelper.UpdateById(firstRecord.Id, new Book("updated first", "aaa_updated", 101));
            Console.WriteLine("updated first record:");
            Console.WriteLine(updatedFirst);


            // add another record 
            var secondRecord = SqliteHelper.Add(new Book("second", "bbb", 200));
            Console.WriteLine("2nd book added :");
            Console.WriteLine(secondRecord);


            // try update by 
            var updatedSecond = SqliteHelper.UpdateBy(
                x=> x.Title == secondRecord.Title && x.Author == secondRecord.Author,
                new Book("updated 2nd", "bbb_updated", 201));


            Console.WriteLine("updated 2nd record:");
            Console.WriteLine(updatedSecond);


            // try delete first
            var deleted = SqliteHelper.DeleteById(firstRecord.Id);
            Console.WriteLine("First record deleted.");


            // All records :
            Console.WriteLine("all records :");
            var all = SqliteHelper.All();
            foreach (var record in all)
            {
                Console.WriteLine(record);
            }


            Console.ReadKey();
        }
    }

 以上就是C# Sqlite 本地存储的详情介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
go语言 注释编码
go语言 注释编码

本专题整合了go语言注释、注释规范等等内容,阅读专题下面的文章了解更多详细内容。

2

2026.01.31

go语言 math包
go语言 math包

本专题整合了go语言math包相关内容,阅读专题下面的文章了解更多详细内容。

1

2026.01.31

go语言输入函数
go语言输入函数

本专题整合了go语言输入相关教程内容,阅读专题下面的文章了解更多详细内容。

1

2026.01.31

golang 循环遍历
golang 循环遍历

本专题整合了golang循环遍历相关教程,阅读专题下面的文章了解更多详细内容。

0

2026.01.31

Golang人工智能合集
Golang人工智能合集

本专题整合了Golang人工智能相关内容,阅读专题下面的文章了解更多详细内容。

1

2026.01.31

2026赚钱平台入口大全
2026赚钱平台入口大全

2026年最新赚钱平台入口汇总,涵盖任务众包、内容创作、电商运营、技能变现等多类正规渠道,助你轻松开启副业增收之路。阅读专题下面的文章了解更多详细内容。

76

2026.01.31

高干文在线阅读网站大全
高干文在线阅读网站大全

汇集热门1v1高干文免费阅读资源,涵盖都市言情、京味大院、军旅高干等经典题材,情节紧凑、人物鲜明。阅读专题下面的文章了解更多详细内容。

73

2026.01.31

无需付费的漫画app大全
无需付费的漫画app大全

想找真正免费又无套路的漫画App?本合集精选多款永久免费、资源丰富、无广告干扰的优质漫画应用,涵盖国漫、日漫、韩漫及经典老番,满足各类阅读需求。阅读专题下面的文章了解更多详细内容。

67

2026.01.31

漫画免费在线观看地址大全
漫画免费在线观看地址大全

想找免费又资源丰富的漫画网站?本合集精选2025-2026年热门平台,涵盖国漫、日漫、韩漫等多类型作品,支持高清流畅阅读与离线缓存。阅读专题下面的文章了解更多详细内容。

19

2026.01.31

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
C# 教程
C# 教程

共94课时 | 8.1万人学习

C 教程
C 教程

共75课时 | 4.3万人学习

C++教程
C++教程

共115课时 | 15万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号