拒绝造轮子(C#篇)使用SqlSugar实现数据库的访问
拒绝造轮子(C#篇)使用SqlSugar实现数据库的访问
SqlSugar 正如其名 SQL糖,提供了非常方便使用和便于理解的SQL语法糖。与LINQ完美结合,高效便捷的实现了数据的增删改查和更加复杂的功能。
该库可以支持多种常用数据库,如下:
public enum DbType
{MySql = 0,SqlServer = 1,Sqlite = 2,Oracle = 3,PostgreSQL = 4,Dm = 5,Kdbndp = 6,Oscar = 7,MySqlConnector = 8,Access = 9,OpenGauss = 10,QuestDB = 11,HG = 12,ClickHouse = 13,GBase = 14,Odbc = 15,OceanBaseForOracle = 16,TDengine = 17,GaussDB = 18,OceanBase = 19,Tidb = 20,Vastbase = 21,PolarDB = 22,Doris = 23,Xugu = 24,GoldenDB = 25,TDSQLForPGODBC = 26,TDSQL = 27,HANA = 28,DB2 = 29,GaussDBNative = 30,DuckDB = 31,MongoDb = 32,Custom = 900
}
后文也介绍了部分数据库的安装,数据库的安装也很简单,对应官网或者问AI都是很快能解决的。
SqlSugar 简单应用
建立连接
public class SqlSugarHelper{public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig(){ConnectionString = "Server=localhost;Database=TestDB;User ID=sa;Password=youpasww@mly2025;TrustServerCertificate=False;Encrypt=True;TrustServerCertificate=True;", DbType = DbType.SqlServer,IsAutoCloseConnection = true },db =>{// 配置AOPdb.Aop.OnLogExecuting = (sql, pars) =>{Console.WriteLine(sql); // 输出SQL语句};});}
ConnectionString 连接字符串(不同数据库不一样)
DbType 数据库类型 MySql SqlServer Sqlite 等
IsAutoCloseConnection 自动关闭连接
创建表
使用SqlSugar创建表分两步奏:
1.建立表实例对象
[SugarTable("Student")] // 指定表名public class Student{[SugarColumn(IsPrimaryKey = true, IsIdentity = true)] // 主键且自增public int Id { get; set; }[SugarColumn(Length = 50)]public string Name { get; set; }public int Age { get; set; }[SugarColumn(Length = 100, IsNullable = true)]public string Email { get; set; }[SugarColumn(IsIgnore = true)] // 不映射到数据库public string DisplayName => $"{Name}({Age})";}
2.在成功建立连接后,自动更新本地实例为数据库的最新结构
public class SqlSugarHelper{public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig(){ConnectionString = "Server=localhost;Database=TestDB;User ID=sa;Password=youpasww@mly2025;TrustServerCertificate=False;Encrypt=True;TrustServerCertificate=True;", DbType = DbType.SqlServer,IsAutoCloseConnection = true },db =>{// 配置AOPdb.Aop.OnLogExecuting = (sql, pars) =>{Console.WriteLine(sql); // 输出SQL语句};// 创建数据库表db.CodeFirst.InitTables(typeof(Student));});}
db.CodeFirst.InitTables(typeof(Student));为创建一个Student表
使用表
SqlSugarScope提供了非常丰富的增删改查功能,支持LINQ语句。非常简洁。下面简单针对Student表进行了简单应用
public class StudentService{public void AddStudent(Student student){using (var db = SqlSugarHelper.Db){db.Insertable(student).ExecuteCommand();}}public Student GetStudent(int id){using (var db = SqlSugarHelper.Db){return db.Queryable<Student>().InSingle(id);}}public List<Student> GetAllStudents(){using (var db = SqlSugarHelper.Db){return db.Queryable<Student>().ToList();}}public void UpdateStudent(Student student){using (var db = SqlSugarHelper.Db){db.Updateable(student).ExecuteCommand();}}public void DeleteStudent(int id){using (var db = SqlSugarHelper.Db){db.Deleteable<Student>().In(id).ExecuteCommand();}}}
应用
MainWindow.xaml.cs
using System.Windows;namespace Gycylm.Tool.Db.App
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();}Db.StudentService service = new Db.StudentService();private void InsertClick(object sender, RoutedEventArgs e){service.AddStudent(new Db.Student(){Name = "张三",Age = 20,Email = "mly@ss.com"});}private void UpdateClick(object sender, RoutedEventArgs e){service.UpdateStudent(new Db.Student(){Id = 1,Name = "李四",Age = 22,Email = "asdas",});}private void DeleteClick(object sender, RoutedEventArgs e){var all= service.GetAllStudents();var deleteId=all.LastOrDefault()?.Id ?? 0;if(deleteId == 0){MessageBox.Show("没有可删除的学生记录");return;}service.DeleteStudent(deleteId);}private void SelectClick(object sender, RoutedEventArgs e){datagrid.ItemsSource = service.GetAllStudents();}}
}
MainWindow.xaml
<Window x:Class="Gycylm.Tool.Db.App.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:Gycylm.Tool.Db.App"mc:Ignorable="d"Title="MainWindow" Height="450" Width="800"><DockPanel><WrapPanel DockPanel.Dock="Top"><Button Content="添加一条" Click="InsertClick"/><Button Content="删除最后一条" Click="DeleteClick"/><Button Content="修改第一条" Click="UpdateClick"/><Button Content="查询结果" Click="SelectClick"/> </WrapPanel><DataGrid x:Name="datagrid"/></DockPanel>
</Window>
总结
如果需要查看更多的使用方法和示例,请搜索SqlSugar或者参考类似以下的学习网站。
https://www.donet5.com/Doc/1/1232
由于提供非常方便的数据库访问,无关SQL。对于用户使用会变得更加轻松。
自动更新最新数据实例,边界更新数据库表结构。同时需要用户确保终端数据模型的变化。
SQLite
无需安装,自动生成对应的数据库文件。(注意下连接字符串的文件地址设置)
MYSQL 安装
省略
SQL Server 安装
安装SQL Server 2022 Developer
下载
https://www.microsoft.com/en-us/sql-server/sql-server-downloads
SQL2022-SSEI-Dev.exe
可以选择基础安装
安装管理工具
下载
SSMS
https://learn.microsoft.com/zh-cn/ssms/install/install?redirectedfrom=MSDN
vs_SSMS.exe
可以选择默认安装
注意和常见问题
1.检查SQL Server配置管理器
步骤:
按Win + R,输入sqlservermanager16.msc(SQL Server 2022使用16)
展开"SQL Server网络配置"
选择"协议"对应您的实例(如"MSSQLSERVER的协议")
确保"Named Pipes"和"TCP/IP"已启用
右键点击每个协议,选择"启用"(如果禁用)
重启SQL Server服务使更改生效
2.检查SQL Server是否允许远程连接
步骤:
使用SSMS成功连接后(或通过以下方法)
右键点击服务器名称,选择"属性"
选择"连接"页
确保"允许远程连接到此服务器"已勾选
3.禁用证书验证(开发环境推荐)
步骤:
打开SQL Server Configuration Manager
展开"SQL Server网络配置"
选择您的实例协议(如"MSSQLSERVER的协议")
右键"属性",转到"证书"选项卡
删除当前分配的证书(设置为空)
转到"标志"选项卡,将"Force Encryption"设为"否"
重启SQL Server服务
4.检查SQL Server身份验证模式
前提:可以使用windows身份正常登录
步骤:
1. 检查SQL Server身份验证模式
首先需要确保SQL Server已启用混合身份验证模式(同时支持Windows和SQL Server身份验证):
使用Windows身份验证登录SSMS
右键点击服务器实例 → 选择"属性"
转到"安全性"页面
确保选择了"SQL Server和Windows身份验证模式"
点击"确定"保存更改
2. 重启SQL Server服务
更改身份验证模式后必须重启服务:
打开"SQL Server配置管理器"
在左侧选择"SQL Server服务"
右键点击您的SQL Server实例 → 选择"重新启动"
3. 检查sa账户状态
在SSMS中展开"安全性" → “登录名”
右键点击"sa"账户 → 选择"属性"
确保:
账户未被禁用(取消勾选"登录已禁用")
密码正确(如需修改密码可在此处设置)
转到"状态"页面,确保"登录"设置为"已启用"
4. 检查服务器网络配置
打开"SQL Server配置管理器"
展开"SQL Server网络配置" → 选择您的实例协议(如"MSSQLSERVER的协议")
确保"TCP/IP"已启用(右键点击选择"启用")
双击"TCP/IP" → 转到"IP地址"选项卡
检查所有IP地址的"已启用"是否为"是"
确保TCP端口正确(通常为1433)
5. 检查防火墙设置
确保防火墙允许SQL Server端口:
打开"Windows Defender防火墙"
选择"高级设置"
创建入站规则:
端口:TCP 1433
允许连接
应用于所有配置文件
6. 测试连接
使用以下连接字符串测试SQL Server身份验证:
Server=localhost;Database=master;User ID=sa;Password=您的密码;TrustServerCertificate=True;
创建一个数据库,例如TestDB