C# WPF 桌面应用程序使用 SQlite 数据库

我们在开发 WPF 桌面应用程序时,数据库存的使用是必不可少的,除非你的应用没有数据存储的需求,有了数据存储需求,我们就会面临使用什么样的数据库的选择问题,我的选择方案是,单机版的应用我优先选择 Sqlite,如果钓多台电脑需要数据共享我优先MySql 8.0+,Sqlite 和MySql 都支持标准的SQL 结构查询语句,数据库的切换也不需要额外大量的开发工作。单机版使用Sqlite ,免去 MySql 安装过程,减少用户的操作,降低使用门槛。

之前的很多应用都是使用 MySql 。现在记录下对 Sqlite 数据的基本使用。

准备两张表和C# 实体类,代码如下
cs 复制代码
   public class BaseEntity
    {
        public Int64 id;
        public Int64 Id
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }
    }
cs 复制代码
    //车辆作息
    public class Car : BaseEntity
    {

        public string carNumber;
        public decimal traeWeight;
        public string driver;
        public string driverMobile;

    }
cs 复制代码
    //货物信息 Material   
    public class Marteral :BaseEntity
    {
        public string name;
        public string firstCase;
    }
对应的表结构
sql 复制代码
CREATE TABLE "main"."marteral" (
"id"  INTEGER NOT NULL,
"name"  TEXT(255) DEFAULT NULL,
"first_case"  TEXT(255) DEFAULT NULL,
PRIMARY KEY ("id" ASC)
);

CREATE TABLE "main"."car" (
"id"  bigint NOT NULL,
"car_number"  TEXT(255) DEFAULT NULL,
"trae_weight"  real(10,3) DEFAULT '0.000',
"driver"  TEXT(255) DEFAULT NULL,
"driver_mobile"  TEXT(255) DEFAULT NULL,
"driver_idnumber"  TEXT(255) DEFAULT NULL,
PRIMARY KEY ("id" ASC)
)
;
第一步 在Nuget中 引入 Sqlite的库。

的代码中引入 命名空间

cs 复制代码
using System.Data;
using Microsoft.Data.Sqlite;
第二步 连接Sqlite。
构建连接字符串
cs 复制代码
       /// <summary>
        /// 
        /// </summary>
        /// <param name="file">sqlite databases file </param>
        /// <returns></returns>
        private static string GetConnString(string file)
        {
            var connStr = new SqliteConnectionStringBuilder()
            {
                DataSource = file,
                Pooling = true,
                // 注意 Mode的值 , SqliteOpenMode.ReadWriteCreate表示不存在文件时
                //会自动创建
                Mode = SqliteOpenMode.ReadWriteCreate,
            }.ConnectionString;

            return connStr;
        }
连接
cs 复制代码
      public bool Connection()
        {
            bool res = false;
            //db file is not exist,
            using (SqliteConnection connection = new SqliteConnection(GetConnString(dbfile)))
            {
                if (connection.State != ConnectionState.Open)
                {

                    connection.Open();
                    res = connection.State == ConnectionState.Open;
                }
            }

            return res;
        }
第三步 使用。
添加数据
cs 复制代码
        //各添加10万条数
        private void InsertBtn_Click(object sender, RoutedEventArgs e)
        {
            int total = 100000;

            for (int i = 0; i < total; i++)
            {
                Marteral m = new Marteral()
                {
                    id = i+1,
                    name = "原煤"+i,
                    firstCase = "YM"+i,
                };
                int res = -1;
                if(i% 2 == 0)
                {
                    string sql = SqlBuilder.GetInsertSql(m);

                     res = SqliteHelper.Instance.Insert(sql);
                }
                else
                {
                     res = SqliteHelper.Instance.Insert(m);
                }
               if(res >= 0)
                {
                    Debug.WriteLine($"{m.name} inseert successed;");
                }
                else
                {
                    Debug.WriteLine($"{m.name} inseert errored;");
                }
            }

            for (int i = 0; i < total; i++)
            {
                Car c= new Car()
                {
                    id = i+1,
                    carNumber = "云DDD73" + i,
                    driver = "驾驶员" + i,
                    driverMobile = "1580874631" +i,
                };
                int res = -1;
                if (i % 2 == 0)
                {
                    string sql = SqlBuilder.GetInsertSql(c);

                    res = SqliteHelper.Instance.Insert(sql);
                }
                else
                {
                    res = SqliteHelper.Instance.Insert(c);
                }
                if (res >= 0)
                {
                    Debug.WriteLine($"{c.carNumber} inseert successed;");
                }
                else
                {
                    Debug.WriteLine($"{c.carNumber} inseert errored;");
                }
            }
        }
修改数据
cs 复制代码
        private void UpdateBtn_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 5; i++)
            {
                Marteral m = new Marteral()
                {
                    id = i + 1,
                    name = "精煤煤" + i,
                    firstCase = "JM" + i,
                };
                int res = -1;
                if (i % 2 == 0)
                {
                    string sql = SqlBuilder.GetUpdateSql(m);

                    res = SqliteHelper.Instance.Update(sql);
                }
                else
                {
                    res = SqliteHelper.Instance.Update(m);
                }
                if (res >= 0)
                {
                    Debug.WriteLine($"{m.name} Update successed;");
                }
                else
                {
                    Debug.WriteLine($"{m.name} Update errored;");
                }
            }

            for (int i = 0; i < 5; i++)
            {
                Car c = new Car()
                {
                    id = i + 1,
                    carNumber = "云AAA73" + i,
                    driver = "驾驶员" + i,
                    driverMobile = "1580874631" + i,
                };
                int res = -1;
                if (i % 2 == 0)
                {
                    string sql = SqlBuilder.GetUpdateSql(c);

                    res = SqliteHelper.Instance.Update(sql);
                }
                else
                {
                    res = SqliteHelper.Instance.Update(c);
                }
                if (res >= 0)
                {
                    Debug.WriteLine($"{c.carNumber} Update successed;");
                }
                else
                {
                    Debug.WriteLine($"{c.carNumber} Update errored;");
                }
            }
        }
删除数据
cs 复制代码
// id % 2 == 0 的数据删除  
private void DeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < 5; i++)
            {
                Marteral m = new Marteral()
                {
                    id = i + 1,
                    name = "精煤煤" + i,
                    firstCase = "JM" + i,
                };
                int res = -1;
                if (i % 2 == 0)
                {
                    string sql = SqlBuilder.GetDeleteSql(m);

                    res = SqliteHelper.Instance.Delete(sql);
                }
              
                if (res >= 0)
                {
                    Debug.WriteLine($"{m.name} Delete successed;");
                }
                else
                {
                    Debug.WriteLine($"{m.name} Delete errored;");
                }
            }

            for (int i = 0; i < 5; i++)
            {
                Car c = new Car()
                {
                    id = i + 1,
                    carNumber = "云AAA73" + i,
                    driver = "驾驶员" + i,
                    driverMobile = "1580874631" + i,
                };
                int res = -1;
                if (i % 2 == 0)
                {
                    string sql = SqlBuilder.GetDeleteSql(c);

                    res = SqliteHelper.Instance.Delete(sql);
                }
              
                if (res >= 0)
                {
                    Debug.WriteLine($"{c.carNumber} Delete successed;");
                }
                else
                {
                    Debug.WriteLine($"{c.carNumber} Delete errored;");
                }
            }
        }
查询并在日志在打印内容
cs 复制代码
      private void SelectBtn_Click(object sender, RoutedEventArgs e)
        {
            string sql = SqlBuilder.GetSelectSql("car", "", "");
            List<Car> cars = SqliteHelper.Instance.Select<Car>(sql);
            cars.ForEach((c) => { Debug.WriteLine(c.carNumber+" trae:"+c.traeWeight); });

            string sql2 = SqlBuilder.GetSelectSql("marteral", "", "");
            List<Marteral> ms = SqliteHelper.Instance.Select<Marteral>(sql2);
            ms.ForEach((m) => { Debug.WriteLine(m.name); });
        }
最后

代码仓库:sqlite_demo: C# WPF 桌面应用程序,数据存储使用Sqlite ,这是一个数据基本操作的基本Demo

感谢各位朋友的阅读,有不足之处,望指正。

相关推荐
Code成立15 分钟前
1、深入理解Redis线程模型
数据库·redis·bootstrap
缘友一世2 小时前
macos安装mongodb
数据库·mongodb·macos
万事大吉CC3 小时前
mysql单表查询·3
数据库·mysql
bin91534 小时前
【EXCEL数据处理】000010 案列 EXCEL文本型和常规型转换。使用的软件是微软的Excel操作的。处理数据的目的是让数据更直观的显示出来,方便查看。
大数据·数据库·信息可视化·数据挖掘·数据分析·excel·数据可视化
Miqiuha4 小时前
lock_guard和unique_lock学习总结
java·数据库·学习
一 乐5 小时前
学籍管理平台|在线学籍管理平台系统|基于Springboot+VUE的在线学籍管理平台系统设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·学习
Java探秘者9 小时前
Maven下载、安装与环境配置详解:从零开始搭建高效Java开发环境
java·开发语言·数据库·spring boot·spring cloud·maven·idea
2301_786964369 小时前
3、练习常用的HBase Shell命令+HBase 常用的Java API 及应用实例
java·大数据·数据库·分布式·hbase
阿维的博客日记10 小时前
图文并茂解释水平分表,垂直分表,水平分库,垂直分库
数据库·分库分表
wrx繁星点点11 小时前
事务的四大特性(ACID)
java·开发语言·数据库