📖 文档概述
本文档详细介绍了 GKTGD 工程中 MySQL 数据库的完整实现,包括连接配置、ORM映射、数据操作、代码原理和移植指南。通过本文档,开发者可以深入理解 MySQL 数据库的工作原理,并将其成功移植到其他项目中。
文档版本 : v1.0
适用项目 : GKTGD 工业控制系统
技术框架 : .NET 8.0 + MySQL 8.0 + SqlSugar ORM
编写日期 : 2026-05-11
数据库版本: MySQL 8.0+
🎯 第一部分:MySQL 数据库基础
1.1 为什么选择 MySQL?
MySQL 核心优势
企业级特性:
- 高可靠性: 支持事务ACID特性,确保数据一致性
- 高性能: 优化的查询引擎,支持百万级数据
- 安全性: 完善的权限管理系统,支持SSL加密连接
- 可扩展性: 支持主从复制、集群架构
- 开源免费: 社区版本完全免费,商业支持可选
适用场景:
- ✅ 用户管理系统: 用户账号、角色权限、登录认证
- ✅ 核心业务数据: 订单、交易、重要配置
- ✅ 需要事务支持: 金融、库存、财务数据
- ✅ 多用户并发: 高并发读写场景
- ✅ 数据关系复杂: 多表关联、外键约束
MySQL vs 其他数据库
| 特性 | MySQL | SQLite | SQL Server | Oracle |
|---|---|---|---|---|
| 部署 | 独立服务器 | 嵌入式 | 独立服务器 | 独立服务器 |
| 并发性能 | ⭐⭐⭐⭐⭐ | ⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 事务支持 | 完整ACID | 完整ACID | 完整ACID | 完整ACID |
| 学习难度 | 中等 | 简单 | 中等 | 困难 |
| 成本 | 开源免费 | 开源免费 | 商业收费 | 商业收费 |
| 适用场景 | 企业应用 | 桌面应用 | 企业应用 | 大型企业 |
1.2 MySQL 安装与配置
Windows 环境安装
步骤1:下载 MySQL Installer
- 访问 MySQL 官网:https://dev.mysql.com/downloads/installer/
- 选择 "mysql-installer-community-8.0.xx.0.msi"
- 下载并运行安装程序
步骤2:安装 MySQL Server
安装类型选择:
┌─────────────────────────────────────┐
│ Developer Default (推荐) │ # 开发者默认,包含所有组件
│ Server only │ # 仅服务器
│ Client only │ # 仅客户端
│ Custom │ # 自定义
└─────────────────────────────────────┘
步骤3:配置 MySQL Server
bash
# 端口配置
Port: 3306 # 默认端口
# root用户密码设置
Root Password: ****** # 请设置强密码
# Windows服务配置
Service Name: MySQL80
Start at System Startup: ✅ # 开机自启动
# 字符集配置
Character Set: utf8mb4 # 支持emoji和中文
Collation: utf8mb4_unicode_ci
步骤4:验证安装
bash
# 打开命令提示符(管理员)
mysql -u root -p
# 输入密码后,如果看到以下信息表示安装成功
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 8.0.xx MySQL Community Server - GPL
mysql>
创建数据库
sql
-- 连接到 MySQL 后执行
CREATE DATABASE gktgd
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
-- 验证数据库创建
SHOW DATABASES;
-- 使用数据库
USE gktgd;
-- 查看字符集
SHOW VARIABLES LIKE 'character%';
输出结果:
+--------------------------+----------------------------+
| Variable_name | Value |
+--------------------------+----------------------------+
| character_set_client | utf8mb4 |
| character_set_connection | utf8mb4 |
| character_set_database | utf8mb4 |
| character_set_filesystem | binary |
| character_set_results | utf8mb4 |
| character_set_server | utf8mb4 |
| character_set_system | utf8mb3 |
+--------------------------+----------------------------+
MySQL 用户权限管理
sql
-- 创建专用数据库用户
CREATE USER 'gktgd_user'@'localhost' IDENTIFIED BY 'YourPassword123!';
-- 授予 gktgd 数据库的所有权限
GRANT ALL PRIVILEGES ON gktgd.* TO 'gktgd_user'@'localhost';
-- 刷新权限
FLUSH PRIVILEGES;
-- 验证用户权限
SHOW GRANTS FOR 'gktgd_user'@'localhost';
-- 回收权限(如需要)
REVOKE ALL PRIVILEGES ON gktgd.* FROM 'gktgd_user'@'localhost';
DROP USER 'gktgd_user'@'localhost';
🔧 第二部分:项目集成配置
2.1 NuGet 包安装
安装 SqlSugarCore
SqlSugar 是一个轻量级、高性能的 .NET ORM 框架,支持 MySQL、SQL Server、SQLite 等多种数据库。
方法1:通过 Visual Studio
- 右键项目 → 管理 NuGet 程序包
- 搜索
SqlSugarCore - 选择版本
5.1.4.214或更高 - 点击 安装
方法2:通过包管理器控制台
powershell
Install-Package SqlSugarCore -Version 5.1.4.214
方法3:通过 .csproj 文件
编辑 NET8_SQLData.csproj:
xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0-windows</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<!-- SqlSugar ORM 核心包 -->
<PackageReference Include="SqlSugarCore" Version="5.1.4.214" />
<!-- 配置文件读取包 -->
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="9.0.7" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.7" />
</ItemGroup>
<ItemGroup>
<!-- 项目引用 -->
<ProjectReference Include="..\NET8_DataConvertLib\NET8_DataConvertLib.csproj" />
</ItemGroup>
</Project>
2.2 连接字符串配置
appsettings.json 配置
文件位置 : GKTGD/appsettings.json
json
{
"ConnectionStrings": {
"LocalMySQL": "Server=localhost;DataBase=gktgd;Port=3306;User Id=root;Password=******;Persist Security Info=True;Allow Zero DateTime=True;Charset=utf8mb4;"
}
}
连接字符串参数详解
| 参数 | 说明 | 示例值 | 必填 |
|---|---|---|---|
| Server | 服务器地址 | localhost | ✅ |
| DataBase | 数据库名称 | gktgd | ✅ |
| Port | 端口号 | 3306 | ❌ (默认3306) |
| User Id | 用户名 | root | ✅ |
| Password | 密码 | ****** | ✅ |
| Persist Security Info | 是否持久化安全信息 | True | ❌ |
| Allow Zero DateTime | 允许零日期时间 | True | ❌ |
| Charset | 字符集 | utf8mb4 | ❌ |
| Connection Timeout | 连接超时时间(秒) | 30 | ❌ |
特殊参数说明:
json
// 完整连接字符串示例
{
"LocalMySQL": "Server=localhost;DataBase=gktgd;Port=3306;User Id=root;Password=RoboTec@123;Persist Security Info=True;Allow Zero DateTime=True;Charset=utf8mb4;Pooling=true;Min Pool Size=5;Max Pool Size=100;Connection Lifetime=0;"
}
// 参数说明
Pooling=true // 启用连接池(推荐)
Min Pool Size=5 // 最小连接数
Max Pool Size=100 // 最大连接数
Connection Lifetime=0 // 连接生命周期(秒),0=不限制
SslMode=None // SSL模式(None/Required/Preferred)
AllowLoadLocalInfile=true // 允许加载本地文件
远程 MySQL 连接配置
json
{
"ConnectionStrings": {
"RemoteMySQL": "Server=192.168.1.100;DataBase=gktgd_remote;Port=3306;User Id=remote_user;Password=RemotePass123!;Persist Security Info=True;Allow Zero DateTime=True;Charset=utf8mb4;SslMode=Preferred;"
}
}
2.3 项目文件结构
NET8_SQLData 项目结构
NET8_SQLData/
├── Core/ # 核心类目录
│ ├── DbManager.cs # 数据库管理器 ⭐
│ ├── DbConfig.cs # 数据库配置模型 ⭐
│ ├── LocalMySQLDb.cs # 本地MySQL静态类 ⭐
│ ├── RemoteMySQLDb.cs # 远程MySQL静态类 ⭐
│ └── LocalSQLiteDb.cs # 本地SQLite静态类
├── Models/ # 数据模型目录
│ └── LocalMySQL/ # MySQL数据模型
│ ├── SQL_UserEntity.cs # 用户实体 ⭐
│ └── SQL_RoleEntity.cs # 角色实体 ⭐
├── Services/ # 服务层目录
│ └── LocalMySQL/ # MySQL服务实现
│ ├── SQL_UserEntity_Service.cs # 用户服务 ⭐
│ └── SQL_RoleEntity_Service.cs # 角色服务 ⭐
├── Interfaces/ # 接口目录
│ ├── IDataService.cs # 数据服务接口
│ └── IRepository.cs # 仓储接口
├── Models/ # 基础模型
│ └── BaseEntity.cs # 实体基类
└── NET8_SQLData.csproj # 项目文件
⭐ 标记: 核心文件,需要重点理解
🏗️ 第三部分:核心代码架构
3.1 DbManager 数据库管理器
完整实现代码
文件位置 : NET8_SQLData/Core/DbManager.cs
csharp
using Microsoft.Extensions.Configuration;
using SqlSugar;
namespace NET8_SQLData.Core
{
/// <summary>
/// 数据库管理器 - 单例模式,管理所有数据库连接
/// </summary>
public static class DbManager
{
private static readonly List<DbConfig> _dbConfigs = new();
private static bool _isInitialized = false;
private static readonly object _lock = new object();
/// <summary>
/// 检查数据库是否已初始化
/// </summary>
public static bool IsInitialized => _isInitialized;
/// <summary>
/// 确保数据库已初始化,如果未初始化则抛出异常
/// </summary>
public static void EnsureInitialized()
{
if (!_isInitialized)
{
throw new InvalidOperationException("数据库未初始化。请先调用 DbManager.Initialize() 方法。");
}
}
/// <summary>
/// 初始化所有数据库连接
/// </summary>
/// <param name="configuration">配置对象(从 appsettings.json 读取)</param>
public static void Initialize(IConfiguration configuration)
{
lock (_lock)
{
if (_isInitialized)
{
System.Diagnostics.Debug.WriteLine("数据库已经初始化,跳过重复初始化");
return;
}
System.Diagnostics.Debug.WriteLine("开始初始化数据库...");
var connectionStrings = configuration.GetSection("ConnectionStrings");
// 读取 LocalMySQL 连接字符串
var localMySQL = connectionStrings["LocalMySQL"];
System.Diagnostics.Debug.WriteLine($"LocalMySQL连接字符串: {(string.IsNullOrEmpty(localMySQL) ? "空" : "已配置")}");
if (!string.IsNullOrEmpty(localMySQL))
{
_dbConfigs.Add(new DbConfig
{
ConnectionString = localMySQL,
DbType = DbType.MySql,
ConfigName = "LocalMySQL"
});
}
// 读取 LocalSQLite 连接字符串
var localSQLite = connectionStrings["LocalSQLite"];
System.Diagnostics.Debug.WriteLine($"LocalSQLite连接字符串: {(string.IsNullOrEmpty(localSQLite) ? "空" : localSQLite)}");
if (!string.IsNullOrEmpty(localSQLite))
{
_dbConfigs.Add(new DbConfig
{
ConnectionString = localSQLite,
DbType = DbType.Sqlite,
ConfigName = "LocalSQLite"
});
}
System.Diagnostics.Debug.WriteLine($"找到 {_dbConfigs.Count} 个数据库配置");
InitializeDbInstances();
_isInitialized = true;
System.Diagnostics.Debug.WriteLine("数据库初始化完成");
}
}
/// <summary>
/// 初始化数据库实例
/// </summary>
private static void InitializeDbInstances()
{
foreach (var config in _dbConfigs)
{
var client = new SqlSugarClient(new ConnectionConfig
{
ConnectionString = config.ConnectionString,
DbType = config.DbType,
IsAutoCloseConnection = config.IsAutoCloseConnection,
InitKeyType = InitKeyType.Attribute
});
// 设置AOP日志
SetupAopLogging(client, config.ConfigName);
// 根据配置名称分配给对应的静态类
switch (config.ConfigName)
{
case "LocalMySQL":
LocalMySQLDb.SetClient(client);
break;
case "LocalSQLite":
LocalSQLiteDb.SetClient(client);
break;
}
}
}
/// <summary>
/// 设置 AOP 日志
/// </summary>
private static void SetupAopLogging(SqlSugarClient client, string configName)
{
// SQL执行前日志
client.Aop.OnLogExecuting = (sql, pars) =>
{
System.Diagnostics.Debug.WriteLine($"[{configName}] 执行SQL: {sql}");
if (pars != null && pars.Length > 0)
{
var paramsInfo = string.Join(", ", pars.Select(p => $"{p.ParameterName}={p.Value}"));
System.Diagnostics.Debug.WriteLine($"[{configName}] SQL参数: {paramsInfo}");
}
};
// SQL错误日志
client.Aop.OnError = (exp) =>
{
System.Diagnostics.Debug.WriteLine($"[{configName}] SQL错误: {exp.Message}");
};
}
/// <summary>
/// 测试数据库连接
/// </summary>
public static bool TestConnection(string configName)
{
try
{
var client = GetClient(configName);
if (client == null) return false;
client.Ado.GetScalar("SELECT 1");
return true;
}
catch
{
return false;
}
}
/// <summary>
/// CodeFirst 创建表
/// </summary>
public static void CreateTables<T>(string configName) where T : class, new()
{
var client = GetClient(configName);
if (client == null)
{
throw new InvalidOperationException($"数据库配置 {configName} 不存在");
}
var config = _dbConfigs.FirstOrDefault(c => c.ConfigName == configName);
client.CodeFirst.SetStringDefaultLength(config?.StringDefaultLength ?? 100).InitTables(typeof(T));
}
/// <summary>
/// 获取指定配置的数据库客户端
/// </summary>
private static SqlSugarClient? GetClient(string configName)
{
return configName switch
{
"LocalMySQL" => LocalMySQLDb.Client,
"LocalSQLite" => LocalSQLiteDb.Client,
_ => null
};
}
}
}
关键设计点
1. 单例模式:
- 使用
static class确保全局唯一 - 使用
lock (_lock)确保线程安全 _isInitialized标志防止重复初始化
2. 延迟初始化:
- 只在实际需要时才创建数据库连接
- 支持多个数据库同时配置
3. AOP 日志:
OnLogExecuting: SQL执行前日志OnError: SQL错误日志- 便于调试和性能优化
4. CodeFirst 支持:
- 自动根据实体类创建数据库表
InitKeyType.Attribute: 使用特性定义主键
3.2 DbConfig 配置模型
csharp
using SqlSugar;
namespace NET8_SQLData.Core
{
/// <summary>
/// 数据库配置模型
/// </summary>
public class DbConfig
{
/// <summary>
/// 连接字符串
/// </summary>
public string ConnectionString { get; set; } = string.Empty;
/// <summary>
/// 数据库类型
/// </summary>
public DbType DbType { get; set; }
/// <summary>
/// 配置名称(如 "LocalMySQL", "LocalSQLite")
/// </summary>
public string ConfigName { get; set; } = string.Empty;
/// <summary>
/// 是否自动关闭连接
/// </summary>
public bool IsAutoCloseConnection { get; set; } = true;
/// <summary>
/// 字符串默认长度
/// </summary>
public int StringDefaultLength { get; set; } = 100;
}
}
3.3 LocalMySQLDb 静态类
文件位置 : NET8_SQLData/Core/LocalMySQLDb.cs
csharp
using SqlSugar;
namespace NET8_SQLData.Core
{
public static class LocalMySQLDb
{
private static SqlSugarClient? _client;
public static SqlSugarClient Client
{
get
{
if (_client == null)
throw new InvalidOperationException("LocalMySQLDb 未初始化,请先调用 DbManager.Initialize()");
return _client;
}
}
internal static void SetClient(SqlSugarClient client) => _client = client;
// CRUD 基础方法
public static List<T> QueryList<T>() where T : class, new() =>
Client.Queryable<T>().ToList();
public static bool Insert<T>(T entity) where T : class, new() =>
Client.Insertable(entity).ExecuteCommand() > 0;
public static bool Update<T>(T entity) where T : class, new() =>
Client.Updateable(entity).ExecuteCommand() > 0;
public static bool Delete<T>(object id) where T : class, new() =>
Client.Deleteable<T>().In(id).ExecuteCommand() > 0;
}
}
设计特点:
- 静态方法: 无需实例化,直接调用
- 泛型支持: 支持任何实体类型
- 简洁API: 封装常用CRUD操作
💾 第四部分:数据模型设计
4.1 实体类定义
用户实体 (SQL_UserEntity)
文件位置 : NET8_SQLData/Models/LocalMySQL/SQL_UserEntity.cs
csharp
using SqlSugar;
namespace NET8_SQLData.Models.LocalMySQL
{
/// <summary>
/// 用户实体
/// </summary>
[SugarTable("Users")] // 映射到数据库表名
public class SQL_UserEntity
{
/// <summary>
/// 用户ID - 主键,自增
/// </summary>
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
/// <summary>
/// 用户名 - 最大50字符
/// </summary>
[SugarColumn(Length = 50)]
public string UserName { get; set; } = string.Empty;
/// <summary>
/// 密码 - 最大100字符
/// </summary>
[SugarColumn(Length = 100)]
public string UserPassword { get; set; } = string.Empty;
/// <summary>
/// 角色ID(外键关联到 Roles 表)
/// </summary>
public int RoleId { get; set; }
/// <summary>
/// 真实姓名 - 可空
/// </summary>
[SugarColumn(Length = 50, IsNullable = true)]
public string? RealName { get; set; }
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; } = true;
/// <summary>
/// 创建时间 - 可空
/// </summary>
[SugarColumn(IsNullable = true)]
public DateTime? CreatedTime { get; set; }
/// <summary>
/// 最后登录时间 - 可空
/// </summary>
[SugarColumn(IsNullable = true)]
public DateTime? LastLoginTime { get; set; }
/// <summary>
/// 导航属性 - 角色信息(查询时自动加载)
/// </summary>
[SugarColumn(IsIgnore = true)] // 不映射到数据库
public SQL_RoleEntity? Role { get; set; }
}
}
SqlSugar 特性详解
| 特性 | 参数 | 说明 | 示例 |
|---|---|---|---|
| [SugarTable] | 表名 | 指定数据库表名 | [SugarTable("Users")] |
| [SugarColumn] | IsPrimaryKey | 是否主键 | IsPrimaryKey = true |
| [SugarColumn] | IsIdentity | 是否自增 | IsIdentity = true |
| [SugarColumn] | Length | 字段长度 | Length = 50 |
| [SugarColumn] | IsNullable | 是否可空 | IsNullable = true |
| [SugarColumn] | IsIgnore | 忽略字段 | IsIgnore = true |
| [SugarColumn] | IsPrimaryKey | 排序 | OrderBy = "desc" |
角色实体 (SQL_RoleEntity)
csharp
using SqlSugar;
namespace NET8_SQLData.Models.LocalMySQL
{
/// <summary>
/// 角色实体
/// </summary>
[SugarTable("Roles")]
public class SQL_RoleEntity
{
/// <summary>
/// 角色ID - 主键,自增
/// </summary>
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
/// <summary>
/// 角色名称 - 最大50字符
/// </summary>
[SugarColumn(Length = 50)]
public string RoleName { get; set; } = string.Empty;
/// <summary>
/// 角色描述 - 最大200字符,可空
/// </summary>
[SugarColumn(Length = 200, IsNullable = true)]
public string? Description { get; set; }
/// <summary>
/// 权限级别 - 数字越大权限越高
/// </summary>
public int PermissionLevel { get; set; } = 0;
/// <summary>
/// 是否启用
/// </summary>
public bool IsEnabled { get; set; } = true;
/// <summary>
/// 创建时间 - 可空
/// </summary>
[SugarColumn(IsNullable = true)]
public DateTime? CreatedTime { get; set; }
/// <summary>
/// 导航属性 - 该角色下的所有用户
/// </summary>
[SugarColumn(IsIgnore = true)]
public List<SQL_UserEntity>? Users { get; set; }
}
}
4.2 数据库表结构
MySQL 表结构(自动创建)
Users 表:
sql
CREATE TABLE `Users` (
`Id` int NOT NULL AUTO_INCREMENT,
`UserName` varchar(50) NOT NULL,
`UserPassword` varchar(100) NOT NULL,
`RoleId` int NOT NULL,
`RealName` varchar(50) DEFAULT NULL,
`IsEnabled` tinyint(1) NOT NULL DEFAULT '1',
`CreatedTime` datetime DEFAULT NULL,
`LastLoginTime` datetime DEFAULT NULL,
PRIMARY KEY (`Id`),
KEY `IX_Users_RoleId` (`RoleId`),
CONSTRAINT `FK_Users_Roles_RoleId` FOREIGN KEY (`RoleId`) REFERENCES `Roles` (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
Roles 表:
sql
CREATE TABLE `Roles` (
`Id` int NOT NULL AUTO_INCREMENT,
`RoleName` varchar(50) NOT NULL,
`Description` varchar(200) DEFAULT NULL,
`PermissionLevel` int NOT NULL DEFAULT '0',
`IsEnabled` tinyint(1) NOT NULL DEFAULT '1',
`CreatedTime` datetime DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
表结构说明:
- ENGINE=InnoDB: 支持事务的存储引擎
- CHARSET=utf8mb4: 支持中文和emoji
- AUTO_INCREMENT: 主键自增
- FOREIGN KEY: 外键约束,确保数据完整性
🚀 第五部分:数据操作服务
5.1 用户服务 (SQL_UserEntity_Service)
完整实现代码
文件位置 : NET8_SQLData/Services/LocalMySQL/SQL_UserEntity_Service.cs
csharp
using NET8_DataConvertLib;
using NET8_SQLData.Core;
using NET8_SQLData.Models.LocalMySQL;
using SqlSugar;
namespace NET8_SQLData.Services.LocalMySQL
{
public class SQL_UserEntity_Service
{
/// <summary>
/// 获取MySQL数据库客户端
/// </summary>
private SqlSugarClient GetClient()
{
try
{
return LocalMySQLDb.Client;
}
catch (InvalidOperationException ex)
{
System.Diagnostics.Debug.WriteLine($"LocalMySQL未初始化: {ex.Message}");
throw new InvalidOperationException(
"用户管理数据必须存储在MySQL数据库。请检查:\n" +
"1. MySQL服务是否启动\n" +
"2. appsettings.json中LocalMySQL配置是否正确\n" +
"3. 数据库'gktgd'是否存在", ex);
}
}
/// <summary>
/// 添加用户
/// </summary>
public OperateResult AddUser(SQL_UserEntity user)
{
try
{
int result = GetClient().Insertable<SQL_UserEntity>(user).ExecuteCommand();
return result == 1
? OperateResult.CreateSuccessResult()
: OperateResult.CreateFailResult("受影响的行数不为1");
}
catch (Exception ex)
{
return OperateResult.CreateFailResult(ex.Message);
}
}
/// <summary>
/// 删除用户
/// </summary>
public OperateResult DeleteUser(int userId)
{
try
{
int result = GetClient().Deleteable<SQL_UserEntity>()
.Where(u => u.Id == userId)
.ExecuteCommand();
return result == 1
? OperateResult.CreateSuccessResult()
: OperateResult.CreateFailResult("受影响的行数不为1");
}
catch (Exception ex)
{
return OperateResult.CreateFailResult(ex.Message);
}
}
/// <summary>
/// 更新用户
/// </summary>
public OperateResult UpdateUser(SQL_UserEntity user)
{
try
{
int result = GetClient().Updateable(user)
.WhereColumns(u => u.Id) // 根据Id更新
.ExecuteCommand();
return result == 1
? OperateResult.CreateSuccessResult()
: OperateResult.CreateFailResult("受影响的行数不为1");
}
catch (Exception ex)
{
return OperateResult.CreateFailResult(ex.Message);
}
}
/// <summary>
/// 获取所有用户(包含角色信息)
/// </summary>
public OperateResult<List<SQL_UserEntity>> GetAllUsers()
{
try
{
var users = GetClient().Queryable<SQL_UserEntity>()
.Mapper(u => u.Role, u => u.RoleId) // 加载关联的角色信息
.ToList();
return OperateResult.CreateSuccessResult(users);
}
catch (Exception ex)
{
return OperateResult.CreateFailResult<List<SQL_UserEntity>>(ex.Message);
}
}
/// <summary>
/// 用户登录验证
/// </summary>
public OperateResult<SQL_UserEntity> UserLogin(string userName, string password)
{
try
{
var user = GetClient().Queryable<SQL_UserEntity>()
.Where(u => u.UserName == userName && u.UserPassword == password && u.IsEnabled)
.First();
if (user != null)
return OperateResult.CreateSuccessResult(user);
else
return OperateResult.CreateFailResult<SQL_UserEntity>("用户名或密码不正确");
}
catch (Exception ex)
{
return OperateResult.CreateFailResult<SQL_UserEntity>(ex.Message);
}
}
/// <summary>
/// 根据ID获取用户
/// </summary>
public OperateResult<SQL_UserEntity> GetUserById(int userId)
{
try
{
var user = GetClient().Queryable<SQL_UserEntity>()
.Where(u => u.Id == userId)
.Mapper(u => u.Role, u => u.RoleId)
.First();
if (user != null)
return OperateResult.CreateSuccessResult(user);
else
return OperateResult.CreateFailResult<SQL_UserEntity>("用户不存在");
}
catch (Exception ex)
{
return OperateResult.CreateFailResult<SQL_UserEntity>(ex.Message);
}
}
/// <summary>
/// 检查用户名是否存在
/// </summary>
public OperateResult<bool> CheckUserNameExists(string userName)
{
try
{
int count = GetClient().Queryable<SQL_UserEntity>()
.Where(u => u.UserName == userName)
.Count();
return OperateResult.CreateSuccessResult(count > 0);
}
catch (Exception ex)
{
return OperateResult.CreateFailResult<bool>(ex.Message);
}
}
}
}
服务方法详解
1. 添加用户 (AddUser)
csharp
// 使用示例
var userService = new SQL_UserEntity_Service();
var newUser = new SQL_UserEntity
{
UserName = "zhangsan",
UserPassword = "123456", // 实际项目中应该加密存储
RoleId = 1,
RealName = "张三",
IsEnabled = true,
CreatedTime = DateTime.Now
};
var result = userService.AddUser(newUser);
if (result.IsSuccess)
{
Console.WriteLine("用户添加成功");
}
else
{
Console.WriteLine($"添加失败: {result.Message}");
}
2. 用户登录 (UserLogin)
csharp
// 使用示例
var userService = new SQL_UserEntity_Service();
var result = userService.UserLogin("zhangsan", "123456");
if (result.IsSuccess)
{
var user = result.Content;
Console.WriteLine($"登录成功: {user.RealName}, 角色: {user.Role?.RoleName}");
}
else
{
Console.WriteLine($"登录失败: {result.Message}");
}
3. 查询所有用户 (GetAllUsers)
csharp
// 使用示例
var userService = new SQL_UserEntity_Service();
var result = userService.GetAllUsers();
if (result.IsSuccess)
{
foreach (var user in result.Content)
{
Console.WriteLine($"{user.UserName} - {user.RealName} - 角色: {user.Role?.RoleName}");
}
}
5.2 SqlSugar 查询语法
基础查询
csharp
// 1. 查询所有
var allUsers = client.Queryable<SQL_UserEntity>().ToList();
// 2. 条件查询
var enabledUsers = client.Queryable<SQL_UserEntity>()
.Where(u => u.IsEnabled)
.ToList();
// 3. 排序
var sortedUsers = client.Queryable<SQL_UserEntity>()
.OrderByDescending(u => u.CreatedTime)
.ToList();
// 4. 分页查询
var pageUsers = client.Queryable<SQL_UserEntity>()
.Skip(10) // 跳过前10条
.Take(20) // 取20条
.ToList();
// 5. 单条查询
var firstUser = client.Queryable<SQL_UserEntity>()
.First();
高级查询
csharp
// 1. 模糊查询
var searchUsers = client.Queryable<SQL_UserEntity>()
.Where(u => u.UserName.Contains("admin"))
.ToList();
// 2. 多条件查询
var filteredUsers = client.Queryable<SQL_UserEntity>()
.Where(u => u.IsEnabled && u.RoleId == 1)
.ToList();
// 3. 聚合查询
var userCount = client.Queryable<SQL_UserEntity>()
.Where(u => u.IsEnabled)
.Count();
// 4. 关联查询
var usersWithRoles = client.Queryable<SQL_UserEntity>()
.Mapper(u => u.Role, u => u.RoleId)
.ToList();
// 5. 投影查询(只查询指定字段)
var userNames = client.Queryable<SQL_UserEntity>()
.Select(u => new { u.UserName, u.RealName })
.ToList();
📱 第六部分:实际应用集成
6.1 App.xaml.cs 数据库初始化
完整初始化流程
文件位置 : GKTGD/App.xaml.cs
csharp
public partial class App : Application
{
private IConfiguration? _configuration;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// 1. 加载配置文件
var builder = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
_configuration = builder.Build();
// 2. 初始化数据库
InitializeDatabase();
// 3. 配置依赖注入
ConfigureServices();
// 4. 显示主窗口
var mainWindow = new MainWindow();
mainWindow.Show();
}
/// <summary>
/// 初始化数据库
/// </summary>
private void InitializeDatabase()
{
try
{
System.Diagnostics.Debug.WriteLine("开始初始化数据库...");
// 初始化数据库管理器
DbManager.Initialize(_configuration);
// 创建数据库表
CreateDatabaseTables();
// 初始化默认数据
InitializeDefaultData();
System.Diagnostics.Debug.WriteLine("数据库初始化成功");
// 测试数据库连接
TestDatabaseConnections();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"数据库初始化失败: {ex.Message}");
MessageBox.Show(
$"⚠️ MySQL数据库初始化失败: {ex.Message}\n\n" +
"用户管理功能将不可用。\n\n" +
"请检查:\n" +
"1. MySQL服务是否启动\n" +
"2. 数据库'gktgd'是否存在\n" +
"3. appsettings.json配置是否正确",
"数据库错误",
MessageBoxButton.OK,
MessageBoxImage.Error);
}
}
/// <summary>
/// 创建数据库表
/// </summary>
private void CreateDatabaseTables()
{
try
{
System.Diagnostics.Debug.WriteLine("在MySQL数据库中创建用户管理表...");
// 检查LocalMySQL是否配置
var localMySQL = _configuration?.GetSection("ConnectionStrings:LocalMySQL").Value;
if (string.IsNullOrEmpty(localMySQL))
{
throw new InvalidOperationException(
"LocalMySQL未配置,无法创建用户管理表。" +
"用户管理数据必须存储在MySQL数据库。");
}
// 创建角色表
DbManager.CreateTables<SQL_RoleEntity>("LocalMySQL");
System.Diagnostics.Debug.WriteLine("角色表创建成功");
// 创建用户表
DbManager.CreateTables<SQL_UserEntity>("LocalMySQL");
System.Diagnostics.Debug.WriteLine("用户表创建成功");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"创建数据库表失败: {ex.Message}");
throw;
}
}
/// <summary>
/// 初始化默认数据
/// </summary>
private void InitializeDefaultData()
{
try
{
var roleService = new SQL_RoleEntity_Service();
var userService = new SQL_UserEntity_Service();
// 检查是否已有默认角色
var existingRoles = roleService.GetAllRoles();
if (!existingRoles.IsSuccess || existingRoles.Content.Count == 0)
{
System.Diagnostics.Debug.WriteLine("初始化默认角色...");
// 创建默认角色
var defaultRoles = new List<SQL_RoleEntity>
{
new SQL_RoleEntity
{
RoleName = "管理员",
Description = "系统管理员,拥有所有权限",
PermissionLevel = 100,
IsEnabled = true,
CreatedTime = DateTime.Now
},
new SQL_RoleEntity
{
RoleName = "工程师",
Description = "工程师,可以配置设备",
PermissionLevel = 50,
IsEnabled = true,
CreatedTime = DateTime.Now
},
new SQL_RoleEntity
{
RoleName = "操作员",
Description = "普通操作员,只能查看数据",
PermissionLevel = 10,
IsEnabled = true,
CreatedTime = DateTime.Now
}
};
foreach (var role in defaultRoles)
{
roleService.AddRole(role);
}
System.Diagnostics.Debug.WriteLine("默认角色创建成功");
}
// 检查是否已有默认用户
var existingUsers = userService.GetAllUsers();
if (!existingUsers.IsSuccess || existingUsers.Content.Count == 0)
{
System.Diagnostics.Debug.WriteLine("初始化默认用户...");
// 获取管理员角色ID
var adminRole = roleService.GetAllRoles().Content.FirstOrDefault(r => r.RoleName == "管理员");
if (adminRole != null)
{
// 创建默认管理员用户
var defaultUser = new SQL_UserEntity
{
UserName = "admin",
UserPassword = "123456", // 实际项目中应该加密存储
RoleId = adminRole.Id,
RealName = "系统管理员",
IsEnabled = true,
CreatedTime = DateTime.Now
};
userService.AddUser(defaultUser);
System.Diagnostics.Debug.WriteLine("默认用户创建成功");
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"初始化默认数据失败: {ex.Message}");
// 不抛出异常,允许应用继续启动
}
}
/// <summary>
/// 测试数据库连接
/// </summary>
private void TestDatabaseConnections()
{
try
{
// 测试 MySQL 连接
bool mysqlConnected = DbManager.TestConnection("LocalMySQL");
System.Diagnostics.Debug.WriteLine($"MySQL连接状态: {(mysqlConnected ? "成功" : "失败")}");
if (!mysqlConnected)
{
MessageBox.Show(
"⚠️ 无法连接到MySQL数据库\n\n" +
"请检查:\n" +
"1. MySQL服务是否启动\n" +
"2. 数据库'gktgd'是否存在\n" +
"3. appsettings.json配置是否正确",
"连接测试",
MessageBoxButton.OK,
MessageBoxImage.Warning);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine($"数据库连接测试失败: {ex.Message}");
}
}
}
6.2 ViewModel 中使用服务
用户管理 ViewModel
文件位置 : GKTGD/ViewModels/UserManagement/UserManagementTask1ViewModel.cs
csharp
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using NET8_SQLData.Models.LocalMySQL;
using NET8_SQLData.Services.LocalMySQL;
using System.Windows;
namespace GKTGD.ViewModels.UserManagement
{
public partial class UserManagementTask1ViewModel : ViewModelBase
{
private readonly SQL_UserEntity_Service _userService;
private readonly SQL_RoleEntity_Service _roleService;
[ObservableProperty]
private List<SQL_UserEntity> _users = new();
[ObservableProperty]
private SQL_UserEntity? _editingUser;
[ObservableProperty]
private string _userName = string.Empty;
[ObservableProperty]
private string _realName = string.Empty;
[ObservableProperty]
private int _selectedRoleId;
public UserManagementTask1ViewModel()
{
_userService = new SQL_UserEntity_Service();
_roleService = new SQL_RoleEntity_Service();
LoadUsers();
}
/// <summary>
/// 加载用户列表
/// </summary>
[RelayCommand]
private void LoadUsers()
{
var result = _userService.GetAllUsers();
if (result.IsSuccess)
{
Users = result.Content;
}
else
{
MessageBox.Show($"加载用户列表失败: {result.Message}", "错误");
}
}
/// <summary>
/// 添加新用户
/// </summary>
[RelayCommand]
private async Task AddNewUserAsync()
{
// 验证输入
if (string.IsNullOrWhiteSpace(UserName))
{
MessageBox.Show("请输入用户名", "验证失败");
return;
}
// 检查用户名是否已存在
var checkResult = _userService.CheckUserNameExists(UserName);
if (checkResult.IsSuccess && checkResult.Content)
{
MessageBox.Show("用户名已存在", "验证失败");
return;
}
// 创建新用户
var newUser = new SQL_UserEntity
{
UserName = UserName,
UserPassword = "123456", // 默认密码,实际项目中应该加密
RoleId = SelectedRoleId,
RealName = RealName,
IsEnabled = true,
CreatedTime = DateTime.Now
};
var result = await Task.Run(() => _userService.AddUser(newUser));
if (result.IsSuccess)
{
MessageBox.Show("用户添加成功", "成功");
LoadUsers(); // 刷新列表
}
else
{
MessageBox.Show($"添加用户失败: {result.Message}", "错误");
}
}
/// <summary>
/// 更新用户
/// </summary>
[RelayCommand]
private async Task UpdateUserAsync()
{
if (EditingUser == null)
{
MessageBox.Show("请先选择要编辑的用户", "提示");
return;
}
// 更新用户信息
EditingUser.RealName = RealName;
EditingUser.RoleId = SelectedRoleId;
var result = await Task.Run(() => _userService.UpdateUser(EditingUser));
if (result.IsSuccess)
{
MessageBox.Show("用户更新成功", "成功");
LoadUsers(); // 刷新列表
}
else
{
MessageBox.Show($"更新用户失败: {result.Message}", "错误");
}
}
/// <summary>
/// 删除用户
/// </summary>
[RelayCommand]
private async Task DeleteUserAsync()
{
if (EditingUser == null)
{
MessageBox.Show("请先选择要删除的用户", "提示");
return;
}
var confirm = MessageBox.Show(
$"确定要删除用户 '{EditingUser.UserName}' 吗?",
"确认删除",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (confirm == MessageBoxResult.Yes)
{
var result = await Task.Run(() => _userService.DeleteUser(EditingUser.Id));
if (result.IsSuccess)
{
MessageBox.Show("用户删除成功", "成功");
LoadUsers(); // 刷新列表
}
else
{
MessageBox.Show($"删除用户失败: {result.Message}", "错误");
}
}
}
}
}
🚀 第七部分:移植指南
7.1 移植到新项目完整步骤
步骤1:创建项目
- 创建新的 WPF 项目或类库项目
- 目标框架:
.NET 8.0-windows
步骤2:安装依赖包
powershell
# 在包管理器控制台执行
Install-Package SqlSugarCore -Version 5.1.4.214
Install-Package Microsoft.Extensions.Configuration.Abstractions -Version 9.0.7
Install-Package Microsoft.Extensions.Configuration.Json -Version 9.0.7
步骤3:复制核心文件
必需文件清单:
NET8_SQLData/
├── Core/
│ ├── DbManager.cs
│ ├── DbConfig.cs
│ └── LocalMySQLDb.cs
├── Interfaces/
│ ├── IDataService.cs
│ └── IRepository.cs
└── NET8_SQLData.csproj
步骤4:配置连接字符串
创建 appsettings.json:
json
{
"ConnectionStrings": {
"LocalMySQL": "Server=localhost;DataBase=your_database;Port=3306;User Id=root;Password=your_password;Persist Security Info=True;Allow Zero DateTime=True;Charset=utf8mb4;"
}
}
步骤5:创建数据模型
csharp
using SqlSugar;
namespace YourProject.Models
{
[SugarTable("YourTable")]
public class YourEntity
{
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
[SugarColumn(Length = 100)]
public string Name { get; set; } = string.Empty;
[SugarColumn(IsNullable = true)]
public DateTime? CreatedTime { get; set; }
}
}
步骤6:创建服务类
csharp
using NET8_SQLData.Core;
using YourProject.Models;
namespace YourProject.Services
{
public class YourEntityService
{
public List<YourEntity> GetAll()
{
return LocalMySQLDb.QueryList<YourEntity>();
}
public bool Add(YourEntity entity)
{
return LocalMySQLDb.Insert(entity);
}
public bool Update(YourEntity entity)
{
return LocalMySQLDb.Update(entity);
}
public bool Delete(int id)
{
return LocalMySQLDb.Delete<YourEntity>(id);
}
}
}
步骤7:初始化数据库
在 App.xaml.cs 中:
csharp
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
// 加载配置
var builder = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
var configuration = builder.Build();
// 初始化数据库
DbManager.Initialize(configuration);
// 创建表
DbManager.CreateTables<YourEntity>("LocalMySQL");
// 显示主窗口
var mainWindow = new MainWindow();
mainWindow.Show();
}
7.2 常见问题和解决方案
问题1:MySQL 连接失败
症状 : Unable to connect to any of the specified MySQL hosts
解决方案:
- 检查 MySQL 服务是否启动
- 检查连接字符串是否正确
- 检查防火墙设置
- 测试连接:
bash
mysql -h localhost -P 3306 -u root -p
问题2:表已存在错误
症状 : Table 'xxx' already exists
解决方案 : SqlSugar 的 InitTables() 会自动检查表是否存在,不会重复创建。
问题3:字符编码问题
症状: 中文乱码
解决方案 : 确保使用 utf8mb4 字符集:
json
{
"LocalMySQL": "Server=localhost;DataBase=gktgd;Charset=utf8mb4;..."
}
问题4:权限不足
症状 : Access denied for user 'xxx'@'localhost'
解决方案: 授予用户权限:
sql
GRANT ALL PRIVILEGES ON your_database.* TO 'your_user'@'localhost';
FLUSH PRIVILEGES;
📊 第八部分:性能优化和最佳实践
8.1 性能优化建议
1. 索引优化
sql
-- 为常用查询字段创建索引
CREATE INDEX IX_Users_UserName ON Users(UserName);
CREATE INDEX IX_Users_RoleId ON Users(RoleId);
-- 查看索引
SHOW INDEX FROM Users;
2. 查询优化
csharp
// ❌ 不好:查询所有数据再筛选
var allUsers = client.Queryable<SQL_UserEntity>().ToList();
var enabledUsers = allUsers.Where(u => u.IsEnabled).ToList();
// ✅ 好:在数据库层面筛选
var enabledUsers = client.Queryable<SQL_UserEntity>()
.Where(u => u.IsEnabled)
.ToList();
3. 连接池配置
json
{
"LocalMySQL": "Server=localhost;DataBase=gktgd;Pooling=true;Min Pool Size=5;Max Pool Size=100;Connection Lifetime=0;..."
}
4. 批量操作
csharp
// 批量插入
var users = new List<SQL_UserEntity>();
// ... 添加多个用户
client.Insertable(users).ExecuteCommand();
// 批量更新
client.Updateable(users).ExecuteCommand();
8.2 安全最佳实践
1. 密码加密
csharp
using System.Security.Cryptography;
using System.Text;
public static class PasswordHelper
{
public static string HashPassword(string password)
{
using (var sha256 = SHA256.Create())
{
var bytes = Encoding.UTF8.GetBytes(password);
var hash = sha256.ComputeHash(bytes);
return Convert.ToBase64String(hash);
}
}
public static bool VerifyPassword(string password, string hash)
{
return HashPassword(password) == hash;
}
}
// 使用示例
var hashedPassword = PasswordHelper.HashPassword("123456");
var user = new SQL_UserEntity
{
UserName = "zhangsan",
UserPassword = hashedPassword // 存储哈希值,不存储明文
};
2. SQL 注入防护
SqlSugar 自动参数化查询,防止 SQL 注入:
csharp
// ✅ 安全:参数化查询
var user = client.Queryable<SQL_UserEntity>()
.Where(u => u.UserName == userName) // 自动参数化
.First();
// ❌ 危险:字符串拼接(不要这样做)
var sql = $"SELECT * FROM Users WHERE UserName = '{userName}'";
3. 连接字符串安全
json
// ❌ 不好:硬编码密码
{
"LocalMySQL": "Server=localhost;DataBase=gktgd;User Id=root;Password=RoboTec@123;"
}
// ✅ 好:使用用户密钥或环境变量
{
"LocalMySQL": "Server=localhost;DataBase=gktgd;User Id=root;Password=${MYSQL_PASSWORD};"
}
📞 第九部分:故障排除和FAQ
9.1 常见错误及解决方案
错误1:Authentication failed
错误信息:
Authentication to host 'localhost' for user 'root' using method 'caching_sha2_password' failed
解决方案:
- 更新用户认证方式:
sql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'RoboTec@123';
FLUSH PRIVILEGES;
- 或修改连接字符串:
json
{
"LocalMySQL": "Server=localhost;DataBase=gktgd;User Id=root;Password=RoboTec@123;AllowPublicKeyRetrieval=True;"
}
错误2:Table doesn't exist
错误信息:
Table 'gktgd.Users' doesn't exist
解决方案:
确保已调用 CreateTables 方法:
csharp
DbManager.CreateTables<SQL_UserEntity>("LocalMySQL");
错误3:Connection timeout
错误信息:
Unable to connect to any of the specified MySQL hosts. Connection timeout
解决方案:
- 检查 MySQL 服务状态:
bash
net start MySQL80
- 增加连接超时时间:
json
{
"LocalMySQL": "Server=localhost;DataBase=gktgd;Connection Timeout=30;..."
}
9.2 调试技巧
1. 启用 SqlSugar 日志
csharp
client.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine($"SQL: {sql}");
Console.WriteLine($"参数: {string.Join(", ", pars.Select(p => $"{p.ParameterName}={p.Value}")))}");
};
2. 测试数据库连接
csharp
public static bool TestConnection()
{
try
{
var client = LocalMySQLDb.Client;
client.Ado.GetScalar("SELECT 1");
return true;
}
catch (Exception ex)
{
Console.WriteLine($"连接失败: {ex.Message}");
return false;
}
}
3. 查看生成的SQL
csharp
var sql = client.Queryable<SQL_UserEntity>()
.Where(u => u.IsEnabled)
.ToSql();
Console.WriteLine($"生成的SQL: {sql}");
🎓 第十部分:进阶主题
10.1 事务处理
csharp
public OperateResult TransferUser(int userId, int newRoleId)
{
try
{
var client = LocalMySQLDb.Client;
// 开启事务
client.Ado.BeginTran();
try
{
// 更新用户角色
client.Updateable<SQL_UserEntity>()
.SetColumns(u => u.RoleId == newRoleId)
.Where(u => u.Id == userId)
.ExecuteCommand();
// 记录操作日志
// ...
// 提交事务
client.Ado.CommitTran();
return OperateResult.CreateSuccessResult();
}
catch
{
// 回滚事务
client.Ado.RollbackTran();
throw;
}
}
catch (Exception ex)
{
return OperateResult.CreateFailResult(ex.Message);
}
}
10.2 复杂查询
csharp
// 多表关联查询
var result = client.Queryable<SQL_UserEntity, SQL_RoleEntity>((u, r) => new object[]
{
JoinType.Left, u.RoleId == r.Id
})
.Select((u, r) => new
{
u.UserName,
u.RealName,
RoleName = r.RoleName
})
.ToList();
// 分组统计
var stats = client.Queryable<SQL_UserEntity>()
.GroupBy(u => u.RoleId)
.Select(u => new
{
RoleId = u.RoleId,
UserCount = SqlFunc.AggregateCount(u.Id)
})
.ToList();
📚 附录
A. SQL 常用命令
sql
-- 查看所有数据库
SHOW DATABASES;
-- 使用数据库
USE gktgd;
-- 查看所有表
SHOW TABLES;
-- 查看表结构
DESCRIBE Users;
-- 查看表创建语句
SHOW CREATE TABLE Users;
-- 删除表
DROP TABLE IF EXISTS Users;
-- 清空表
TRUNCATE TABLE Users;
-- 删除数据库
DROP DATABASE IF EXISTS gktgd;
B. MySQL 数据类型对照
| C# 类型 | MySQL 类型 | 说明 |
|---|---|---|
int |
INT |
32位整数 |
long |
BIGINT |
64位整数 |
string |
VARCHAR(n) |
可变长度字符串 |
string |
TEXT |
长文本 |
DateTime |
DATETIME |
日期时间 |
bool |
TINYINT(1) |
布尔值 |
decimal |
DECIMAL |
精确数值 |
byte[] |
BLOB |
二进制数据 |
C. 参考资料
- SqlSugar 官方文档: https://www.donet5.com/
- MySQL 官方文档: https://dev.mysql.com/doc/
- .NET 8.0 文档: https://docs.microsoft.com/en-us/dotnet/
文档结束
本文档详细介绍了 GKTGD 工程中 MySQL 数据库的完整实现,包括安装配置、连接管理、数据操作、代码原理和移植指南。通过本文档,开发者可以快速上手 MySQL 数据库开发,并将其成功移植到其他项目中。
文档版本 : v1.0
最后更新: 2026-05-11