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

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

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

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

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

    }
    //货物信息 Material   
    public class Marteral :BaseEntity
    {
        public string name;
        public string firstCase;
    }

 

对应的表结构
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的库。

的代码中引入 命名空间

using System.Data;
using Microsoft.Data.Sqlite;
第二步 连接Sqlite。
构建连接字符串
       /// <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;
        }
连接
      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;
        }
第三步  使用。

        添加数据
        //各添加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;");
                }
            }
        }
        修改数据

        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;");
                }
            }
        }

        删除数据

        

// 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;");
                }
            }
        }
查询并在日志在打印内容

      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

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

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要在 WPF 应用程序中连接数据库,可以按照以下步骤进行: 1. 在 Visual Studio 中创建一个 WPF 应用程序项目。 2. 在项目中添加一个数据源,可以选择数据库、服务或对象。 3. 在数据源配置向导中选择要连接的数据库类型,并输入连接字符串、用户名和密码等信息。 4. 在项目中创建一个数据上下文类,用于获取和保存数据库中的数据。 5. 在 XAML 中创建一个数据绑定,将 UI 控件和数据上下文关联起来。 下面是一个简单的示例: 1. 在 Visual Studio 中创建一个 WPF 应用程序项目。 2. 在解决方案资源管理器中右键单击项目,选择“添加”->“新建项”->“数据”->“数据源”。 3. 在数据源配置向导中选择“数据库”类型,然后输入连接字符串、用户名和密码等信息。 4. 在下一步中选择要连接的数据库表,并设置主键、排序等信息。 5. 完成向导后,会生成一个数据集和一个表适配器,可以用来获取和保存数据库中的数据。 6. 在项目中创建一个数据上下文类,用于获取和保存数据。可以使用以下代码: ```csharp using System.Data.Entity; public class MyDataContext : DbContext { public DbSet<MyData> MyDataSet { get; set; } } ``` 其中 `MyData` 是要保存的数据类型。 7. 在 XAML 中创建一个数据绑定,将 UI 控件和数据上下文关联起来。可以使用以下代码: ```xaml <Window x:Class="MyApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:MyApp" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <ObjectDataProvider ObjectType="{x:Type local:MyDataContext}" x:Key="MyDataContext"/> </Window.Resources> <Grid DataContext="{Binding Source={StaticResource MyDataContext}}"> <DataGrid ItemsSource="{Binding MyDataSet}" AutoGenerateColumns="True"/> </Grid> </Window> ``` 其中 `MyDataContext` 是上一步创建的数据上下文类,`MyDataSet` 是要显示的数据集。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值