2025-11-14
SQLite
00

目录

项目架构概述
项目依赖
详细实现步骤
数据库连接管理
设备配置模型
3. 配置管理服务
使用Spectre.Console美化控制台演示
注意事项与最佳实践
总结

📱 轻松管理各类设备参数配置 💾 SQLite本地数据持久化存储 🚀 简单易用的C#实现方案 🛠️ 适用于工业自动化、物联网设备管理

在工业自动化、设备监控、物联网应用等领域,如何高效管理各种设备的参数配置始终是一个重要问题。本文将详细介绍如何使用C#和SQLite数据库构建一个轻量级但功能强大的设备参数配置管理系统。无论你是想为工业设备创建管理软件,还是开发物联网项目,这套解决方案都能帮你轻松管理各类设备参数。

项目架构概述

本项目采用简洁的三层架构设计,包括:

  1. 数据层:SQLite数据库连接管理和基础操作
  2. 模型层:设备配置的实体类定义
  3. 业务逻辑层:配置管理服务,提供增删改查功能

这种架构让系统易于理解、维护和扩展,适合中小型项目快速实现和迭代。

项目依赖

要运行此项目,需要安装以下NuGet包:

Markdown
System.Data.SQLite Spectre.Console

详细实现步骤

数据库连接管理

首先,我们需要创建数据库连接管理类,负责SQLite数据库的创建、连接和初始化:

C#
using System; using System.Collections.Generic; using System.Data.SQLite; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppDeviceConfig { /// <summary> /// 数据库连接管理类,负责SQLite数据库的创建和连接 /// </summary> public class DatabaseManager { // 数据库文件路径 private const string DATABASE_PATH = "DeviceConfig.sqlite"; /// <summary> /// 创建并返回SQLite数据库连接 /// </summary> /// <returns>打开的SQLite连接</returns> public static SQLiteConnection CreateConnection() { // 如果数据库文件不存在则创建 if (!File.Exists(DATABASE_PATH)) { SQLiteConnection.CreateFile(DATABASE_PATH); } // 创建并打开连接 var connection = new SQLiteConnection($"Data Source={DATABASE_PATH};Version=3;"); connection.Open(); return connection; } /// <summary> /// 初始化数据库,创建必要的表结构 /// </summary> public static void InitializeDatabase() { using (var connection = CreateConnection()) { // 创建设备配置表,如果表不存在的话 string createDeviceTableSql = @" CREATE TABLE IF NOT EXISTS DeviceConfigurations ( Id INTEGER PRIMARY KEY AUTOINCREMENT, DeviceType TEXT NOT NULL, DeviceName TEXT NOT NULL, ConfigKey TEXT NOT NULL, ConfigValue TEXT NOT NULL, LastUpdated DATETIME DEFAULT CURRENT_TIMESTAMP, UNIQUE(DeviceType, DeviceName, ConfigKey) )"; using (var command = new SQLiteCommand(createDeviceTableSql, connection)) { command.ExecuteNonQuery(); } } } } }

设备配置模型

接下来,定义设备配置的数据模型,用于表示设备参数的实体:

C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppDeviceConfig { /// <summary> /// 设备配置实体类,表示单个设备参数的配置信息 /// </summary> public class DeviceConfiguration { /// <summary>配置项唯一标识符</summary> public int Id { get; set; } /// <summary>设备类型,例如:变频器、电机控制器等</summary> public string DeviceType { get; set; } /// <summary>设备名称,用于标识具体设备</summary> public string DeviceName { get; set; } /// <summary>配置项键名</summary> public string ConfigKey { get; set; } /// <summary>配置项值</summary> public string ConfigValue { get; set; } /// <summary>最后更新时间</summary> public DateTime LastUpdated { get; set; } } }

3. 配置管理服务

配置管理服务是系统的核心,提供对设备配置的各种操作:

C#
using System; using System.Collections.Generic; using System.Data.SQLite; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppDeviceConfig { /// <summary> /// 配置管理服务,提供设备配置的增删改查功能 /// </summary> public class ConfigurationService { /// <summary> /// 保存或更新设备配置 /// </summary> /// <param name="config">要保存的设备配置</param> public void SaveDeviceConfiguration(DeviceConfiguration config) { using (var connection = DatabaseManager.CreateConnection()) { // 使用INSERT OR REPLACE语法实现更新或插入 string insertSql = @" INSERT OR REPLACE INTO DeviceConfigurations (DeviceType, DeviceName, ConfigKey, ConfigValue) VALUES (@DeviceType, @DeviceName, @ConfigKey, @ConfigValue)"; using (var command = new SQLiteCommand(insertSql, connection)) { command.Parameters.AddWithValue("@DeviceType", config.DeviceType); command.Parameters.AddWithValue("@DeviceName", config.DeviceName); command.Parameters.AddWithValue("@ConfigKey", config.ConfigKey); command.Parameters.AddWithValue("@ConfigValue", config.ConfigValue); command.ExecuteNonQuery(); } } } /// <summary> /// 获取特定设备的特定配置项 /// </summary> /// <param name="deviceType">设备类型</param> /// <param name="deviceName">设备名称</param> /// <param name="configKey">配置项键名</param> /// <returns>设备配置对象,未找到时返回null</returns> public DeviceConfiguration GetDeviceConfiguration(string deviceType, string deviceName, string configKey) { using (var connection = DatabaseManager.CreateConnection()) { string selectSql = @" SELECT * FROM DeviceConfigurations WHERE DeviceType = @DeviceType AND DeviceName = @DeviceName AND ConfigKey = @ConfigKey"; using (var command = new SQLiteCommand(selectSql, connection)) { command.Parameters.AddWithValue("@DeviceType", deviceType); command.Parameters.AddWithValue("@DeviceName", deviceName); command.Parameters.AddWithValue("@ConfigKey", configKey); using (var reader = command.ExecuteReader()) { if (reader.Read()) { return new DeviceConfiguration { Id = Convert.ToInt32(reader["Id"]), DeviceType = reader["DeviceType"].ToString(), DeviceName = reader["DeviceName"].ToString(), ConfigKey = reader["ConfigKey"].ToString(), ConfigValue = reader["ConfigValue"].ToString(), LastUpdated = Convert.ToDateTime(reader["LastUpdated"]) }; } } } } return null; } /// <summary> /// 获取特定类型设备的所有配置 /// </summary> /// <param name="deviceType">设备类型</param> /// <returns>设备配置列表</returns> public List<DeviceConfiguration> GetDeviceConfigurations(string deviceType) { var configurations = new List<DeviceConfiguration>(); using (var connection = DatabaseManager.CreateConnection()) { string selectSql = "SELECT * FROM DeviceConfigurations WHERE DeviceType = @DeviceType"; using (var command = new SQLiteCommand(selectSql, connection)) { command.Parameters.AddWithValue("@DeviceType", deviceType); using (var reader = command.ExecuteReader()) { while (reader.Read()) { configurations.Add(new DeviceConfiguration { Id = Convert.ToInt32(reader["Id"]), DeviceType = reader["DeviceType"].ToString(), DeviceName = reader["DeviceName"].ToString(), ConfigKey = reader["ConfigKey"].ToString(), ConfigValue = reader["ConfigValue"].ToString(), LastUpdated = Convert.ToDateTime(reader["LastUpdated"]) }); } } } } return configurations; } /// <summary> /// 删除特定设备配置 /// </summary> /// <param name="deviceType">设备类型</param> /// <param name="deviceName">设备名称</param> /// <param name="configKey">配置项键名</param> /// <returns>是否删除成功</returns> public bool DeleteDeviceConfiguration(string deviceType, string deviceName, string configKey) { using (var connection = DatabaseManager.CreateConnection()) { string deleteSql = @" DELETE FROM DeviceConfigurations WHERE DeviceType = @DeviceType AND DeviceName = @DeviceName AND ConfigKey = @ConfigKey"; using (var command = new SQLiteCommand(deleteSql, connection)) { command.Parameters.AddWithValue("@DeviceType", deviceType); command.Parameters.AddWithValue("@DeviceName", deviceName); command.Parameters.AddWithValue("@ConfigKey", configKey); int rowsAffected = command.ExecuteNonQuery(); return rowsAffected > 0; } } } } }

使用Spectre.Console美化控制台演示

Spectre.Console是一个强大的.NET库,可以创建美观的控制台应用。下面我们使用它来展示我们的系统功能:

C#
using System.Drawing; using Spectre.Console; namespace AppDeviceConfig { internal class Program { static void Main(string[] args) { // 显示标题 AnsiConsole.Write( new FigletText("设备配置管理系统") .Centered() .Color(Spectre.Console.Color.Orange1)); AnsiConsole.WriteLine(); AnsiConsole.MarkupLine("[bold yellow]欢迎使用设备参数配置管理系统[/]"); AnsiConsole.WriteLine(); // 初始化数据库 AnsiConsole.Status() .Start("正在初始化系统...", ctx => { ctx.Spinner(Spinner.Known.Star); ctx.SpinnerStyle(Style.Parse("green")); DatabaseManager.InitializeDatabase(); System.Threading.Thread.Sleep(1000); // 演示用延时 }); var configService = new ConfigurationService(); // 使用Spectre.Console的表格显示演示数据 var table = new Table(); table.AddColumn("设备类型"); table.AddColumn("设备名称"); table.AddColumn("参数名"); table.AddColumn("参数值"); // 示例1:保存变频器配置 AnsiConsole.Status() .Start("正在添加示例配置...", ctx => { // 添加变频器配置 configService.SaveDeviceConfiguration(new DeviceConfiguration { DeviceType = "变频器", DeviceName = "主轴变频器", ConfigKey = "频率", ConfigValue = "50.5" }); configService.SaveDeviceConfiguration(new DeviceConfiguration { DeviceType = "变频器", DeviceName = "副轴变频器", ConfigKey = "频率", ConfigValue = "60.0" }); // 添加电机控制器配置 configService.SaveDeviceConfiguration(new DeviceConfiguration { DeviceType = "电机控制器", DeviceName = "主电机控制器", ConfigKey = "最大转速", ConfigValue = "3000" }); configService.SaveDeviceConfiguration(new DeviceConfiguration { DeviceType = "电机控制器", DeviceName = "主电机控制器", ConfigKey = "启动模式", ConfigValue = "软启动" }); configService.SaveDeviceConfiguration(new DeviceConfiguration { DeviceType = "传感器", DeviceName = "温度传感器", ConfigKey = "报警阈值", ConfigValue = "85" }); System.Threading.Thread.Sleep(1000); // 演示用延时 }); // 获取并显示所有变频器配置 var deviceTypes = new[] { "变频器", "电机控制器", "传感器" }; foreach (var deviceType in deviceTypes) { var configs1 = configService.GetDeviceConfigurations(deviceType); foreach (var config in configs1) { table.AddRow( config.DeviceType, config.DeviceName, config.ConfigKey, config.ConfigValue ); } } AnsiConsole.WriteLine(); AnsiConsole.MarkupLine("[bold green]当前系统中的设备配置:[/]"); AnsiConsole.Write(table); // 演示查询特定配置 AnsiConsole.WriteLine(); var selectedDeviceType = AnsiConsole.Prompt( new SelectionPrompt<string>() .Title("请选择要查看的[green]设备类型[/]") .PageSize(10) .AddChoices(deviceTypes)); var configs = configService.GetDeviceConfigurations(selectedDeviceType); if (configs.Any()) { // 创建树形结构展示设备配置 var root = new Tree($"[yellow]{selectedDeviceType}[/]"); var deviceNames = configs.Select(c => c.DeviceName).Distinct(); foreach (var deviceName in deviceNames) { var deviceNode = root.AddNode($"[blue]{deviceName}[/]"); var deviceConfigs = configs.Where(c => c.DeviceName == deviceName); foreach (var config in deviceConfigs) { deviceNode.AddNode($"[green]{config.ConfigKey}[/]: [white]{config.ConfigValue}[/]"); } } AnsiConsole.Write(root); } else { AnsiConsole.MarkupLine($"[yellow]未找到{selectedDeviceType}的配置信息[/]"); } // 演示修改配置 AnsiConsole.WriteLine(); if (AnsiConsole.Confirm("是否要修改主轴变频器的频率?")) { var newValue = AnsiConsole.Ask<string>("请输入新的频率值:", "45.0"); configService.SaveDeviceConfiguration(new DeviceConfiguration { DeviceType = "变频器", DeviceName = "主轴变频器", ConfigKey = "频率", ConfigValue = newValue }); var updatedConfig = configService.GetDeviceConfiguration("变频器", "主轴变频器", "频率"); AnsiConsole.MarkupLine($"[green]配置已更新:[/] 新频率 = {updatedConfig.ConfigValue}"); } AnsiConsole.WriteLine(); AnsiConsole.MarkupLine("[bold blue]演示完成,感谢使用设备参数配置管理系统![/]"); } } }

image.png

注意事项与最佳实践

  1. 正确处理数据库连接:使用using语句确保连接正确关闭
  2. 参数化查询:避免SQL注入风险
  3. 异常处理:在实际应用中添加完善的错误处理机制
  4. 参数验证:添加配置参数的数据验证逻辑
  5. 考虑配置加密:敏感配置信息应当加密存储

总结

本文介绍了如何使用C#和SQLite实现一个功能完善的设备参数配置管理系统。通过简洁的架构设计和SQLite数据库的高效存储,系统能够满足各类设备参数管理的需求。Spectre.Console的应用使得控制台演示更加直观和美观。

无论是工业自动化、物联网设备管理还是其他需要参数配置的场景,这套系统都能提供一个可靠、高效且易于扩展的解决方案。希望这篇文章能为你的项目提供有价值的参考!

关键词:C#配置管理、SQLite数据库、设备参数管理、工业自动化、物联网设备、Spectre.Console、控制台应用美化

欢迎在评论区分享您的应用场景和改进建议!

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!