背景:
在gitee上发现了神仙仓库,决定拿来试一下,上b站查了各种资料,全是某套皮培训班的资料,遂写下这篇,方便快速了解这个SqlSugar,以及快速上手,本人也是初学者,不喜勿喷,附果糖网官方文档,SqlSugar .Net ORM 5.X 官网 、文档、教程 - SqlSugar 5x - .NET果糖网;果糖网官方仓库 https://gitee.com/dotnetchina/SqlSugar.git
准备工作:
需要在解决方案下安装Nuget包,sqlsugarCore,版本随缘选择,我是选择最新的
创建WPF项目,随便新建一个就行,环境我是.NET8.0
需要创建的文件有:
1、ConnectionConfig.json,配置连接字符串
2、UserData.db ,sqlite的数据库文件
3、SqliteDbHelper.cs,用于解析json文件中存放的数据库路径并且创建SqlSugar连接配置
4、UserInfo.cs,和数据库一一对应的表,我在数据库只放了一张表,所以只有建一个类
文件目录预览
需要注意,json文件和db文件的文件属性需要设置为“如果较新则复制”,他才会生成到根目录的文件夹下
正式开始
1、编写连接字符串
这个./的意思是在根目录下的文件夹
{
"ConnectionStrings": {
"SqliteConnection": "Data Source=./Config/UserData.db"
}
}
2、创建数据库的表头
放了两条初始数据
3、创建对应的类文件
数据库的表头要和类文件一一对应
namespace SqlSugarToSqlite.SqlConfig
{
[SugarTable("UserInfo")] // 指定数据库表名
public class UserInfo
{
/// <summary>
/// 主键ID,确保IsIdentity=true,且不要手动设置此值
/// </summary>
[SugarColumn(IsPrimaryKey = true, IsIdentity = true)]
public int Id { get; set; }
/// <summary>
/// 索引字段
/// </summary>
[SugarColumn(ColumnName = "index")] // 与数据库字段名映射
public string Index { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string Username { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 邮箱
/// </summary>
public string Email { get; set; }
/// <summary>
/// 地区
/// </summary>
public string Region { get; set; }
/// <summary>
/// 电话号码
/// </summary>
public string Phonenumber { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; } = DateTime.Now;
}
}
4、编写SqlitDbHelper
主要是实现json文件解析,核心是创建Sqlsugar连接配置,如果不想写这么多,直接给出数据库的路径给到dbPath即可
_db = new SqlSugarClient(new ConnectionConfig
{
ConnectionString = $"Data Source={dbPath}",
DbType = DbType.Sqlite,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
namespace SqlSugarToSqlite.SqlConfig
{
public class SqliteDbHelper
{
private static SqlSugarClient _db;
private static readonly object LockObject = new object();
public static SqlSugarClient Db
{
get
{
if (_db == null)
{
lock (LockObject)
{
if (_db == null)
{
InitializeDb();
}
}
}
return _db;
}
}
private static void InitializeDb()
{
try
{
// 读取配置文件
string configPath = Path.Combine(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
"Config",
"ConnectionConfig.json");
if (!File.Exists(configPath))
{
throw new FileNotFoundException("找不到数据库配置文件", configPath);
}
// 解析JSON配置
dynamic config = Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText(configPath));
string connectionString = config.ConnectionStrings.SqliteConnection.ToString();
// 确保数据库文件路径正确
string dbPath = connectionString.Split('=')[1].Split(';')[0].Trim();
if (!Path.IsPathRooted(dbPath))
{
dbPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), dbPath);
}
if (!File.Exists(dbPath))
{
throw new FileNotFoundException("找不到SQLite数据库文件", dbPath);
}
// 创建SqlSugar连接配置
_db = new SqlSugarClient(new ConnectionConfig
{
ConnectionString = $"Data Source={dbPath}",
DbType = DbType.Sqlite,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute
});
}
catch (Exception ex)
{
Console.WriteLine($"数据库初始化失败: {ex.Message}");
throw;
}
}
}
}
5、选择连接方式
可以选择在app加载的时候直接开始连接,也可以通过按钮来连接,我使用的是一进入程序就自己连接,要在app.cs文件中编写
namespace SqlSugarToSqlite
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
try
{
// 初始化数据库连接
var db = SqlConfig.SqliteDbHelper.Db;
}
catch (Exception ex)
{
MessageBox.Show($"数据库连接失败: {ex.Message}", "错误",
MessageBoxButton.OK, MessageBoxImage.Error);
Shutdown();
return;
}
base.OnStartup(e);
}
}
}
通过按钮点击事件来连接
private void Button_Click(object sender, RoutedEventArgs e)
{
var db = SqlConfig.SqliteDbHelper.Db;
var users = db.Queryable<UserInfo>().ToList();
us_Datagrid.ItemsSource = users;
}
6、基本界面制作,实现增删改查
6.1 基本页面制作
这个页面由datagrid(展示数据库中的内容),几个TextBox(对应更改的内容),和四个增删改查的按钮,以及一个模糊查询的textbox
MainWindow的xaml代码:
<Window x:Class="SqlSugarToSqlite.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:SqlSugarToSqlite"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="900">
<Grid>
<DataGrid x:Name="us_Datagrid" Height="300" VerticalAlignment="Top">
</DataGrid>
<StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" Height="50" Margin="0,0,0,50">
<Label Content="Index" VerticalContentAlignment="Center" FontSize="15"/>
<TextBox x:Name="Id_Text" Width="50" Height="30" VerticalContentAlignment="Center" FontSize="15"/>
<Label Content="UserName" VerticalContentAlignment="Center" FontSize="15"/>
<TextBox x:Name="UserName_Text" Width="100" Height="30" VerticalContentAlignment="Center" FontSize="15"/>
<Label Content="Age" VerticalContentAlignment="Center" FontSize="15"/>
<TextBox x:Name="Age_Text" Width="50" Height="30" VerticalContentAlignment="Center" FontSize="15"/>
<Label Content="Email" VerticalContentAlignment="Center" FontSize="15"/>
<TextBox x:Name="Email_Text" Width="100" Height="30" VerticalContentAlignment="Center" FontSize="15"/>
<Label Content="Region" VerticalContentAlignment="Center" FontSize="15"/>
<TextBox x:Name="Region_Text" Width="100" Height="30" VerticalContentAlignment="Center" FontSize="15"/>
<Label Content="PhoneNumber" VerticalContentAlignment="Center" FontSize="15"/>
<TextBox x:Name="PhoneNumber_Text" Width="100" Height="30" VerticalContentAlignment="Center" FontSize="15"/>
</StackPanel>
<StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" Height="40" >
<Button Content="增加" Width="150" Click="Add_Click" VerticalContentAlignment="Center" FontSize="15"/>
<Button Content="删除" Width="150" Click="Remove_Click" VerticalContentAlignment="Center" FontSize="15" Margin="10,0,0,0"/>
<Button Content="更改" Width="150" Click="Change_Click" VerticalContentAlignment="Center" FontSize="15" Margin="10,0,0,0"/>
<TextBox x:Name="Search_Text" VerticalContentAlignment="Center" Width="150" Margin="10,0,0,0" Background="AliceBlue"/>
<Button Content="查询" Width="50" Click="Search_Click" VerticalContentAlignment="Center" FontSize="15" Margin="10,0,0,0"/>
</StackPanel>
</Grid>
</Window>
MainWindow的cs代码
using SqlSugarToSqlite.SqlConfig;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SqlSugarToSqlite
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadUserData();
this.us_Datagrid.SelectionChanged += us_Datagrid_SelectionChanged;
}
private void LoadUserData()
{
try
{
var db = SqliteDbHelper.Db;
var users = db.Queryable<UserInfo>().ToList();
us_Datagrid.ItemsSource = users;
}
catch (Exception ex)
{
MessageBox.Show($"加载数据失败: {ex.Message}", "错误",MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void us_Datagrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedUser = us_Datagrid.SelectedItem as UserInfo;
if (selectedUser != null)
{
Id_Text.Text = selectedUser.Index;
UserName_Text.Text = selectedUser.Username;
Age_Text.Text = selectedUser.Age.ToString();
Email_Text.Text = selectedUser.Email;
Region_Text.Text = selectedUser.Region;
PhoneNumber_Text.Text = selectedUser.Phonenumber;
}
}
private void Add_Click(object sender, RoutedEventArgs e)
{
try
{
var newUser = new UserInfo
{
Index = Id_Text.Text,
Username = UserName_Text.Text,
Age = int.Parse(Age_Text.Text),
Email = Email_Text.Text,
Region = Region_Text.Text,
Phonenumber = PhoneNumber_Text.Text,
CreateTime = DateTime.Now
};
var db = SqliteDbHelper.Db;
db.Insertable(newUser).ExecuteCommand();
MessageBox.Show("用户添加成功", "成功",MessageBoxButton.OK, MessageBoxImage.Information);
LoadUserData();
}
catch (Exception ex)
{
MessageBox.Show($"添加用户失败: {ex.Message}", "错误",MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void Remove_Click(object sender, RoutedEventArgs e)
{
// 获取选中的用户
var selectedUser = us_Datagrid.SelectedItem as UserInfo;
if (selectedUser == null)
{
MessageBox.Show("请先选择要删除的用户", "提示",MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
// 确认删除
if (MessageBox.Show($"确定要删除用户 '{selectedUser.Username}' 吗?", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
{
return;
}
try
{
var db = SqliteDbHelper.Db;
// 执行删除
int affectedRows = db.Deleteable(selectedUser).ExecuteCommand();
if (affectedRows > 0)
{
MessageBox.Show("用户删除成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
LoadUserData(); // 重新加载数据
}
else
{
MessageBox.Show("用户删除失败,可能已被其他操作删除", "错误",MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex)
{
MessageBox.Show($"删除用户失败: {ex.Message}", "错误",MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void Change_Click(object sender, RoutedEventArgs e)
{
// 获取选中的用户
var selectedUser = us_Datagrid.SelectedItem as UserInfo;
if (selectedUser == null)
{
MessageBox.Show("请先选择要修改的用户", "提示",MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
try
{
// 更新用户信息
selectedUser.Index = Id_Text.Text;
selectedUser.Username = UserName_Text.Text;
selectedUser.Age = int.Parse(Age_Text.Text);
selectedUser.Email = Email_Text.Text;
selectedUser.Region = Region_Text.Text;
selectedUser.Phonenumber = PhoneNumber_Text.Text;
selectedUser.CreateTime = DateTime.Now;
var db = SqliteDbHelper.Db;
// 执行更新
int affectedRows = db.Updateable(selectedUser).ExecuteCommand();
if (affectedRows > 0)
{
MessageBox.Show("用户信息修改成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
LoadUserData(); // 重新加载数据
}
else
{
MessageBox.Show("用户信息修改失败,数据未变更", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex)
{
MessageBox.Show($"修改用户失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void Search_Click(object sender, RoutedEventArgs e)
{
string searchKeyword = Search_Text.Text.Trim();
if (string.IsNullOrEmpty(searchKeyword))
{
// 无搜索关键词时显示全部数据
LoadUserData();
return;
}
try
{
var db = SqliteDbHelper.Db;
// 多字段模糊查询(Index、Username、Email、Region、Phonenumber)
var users = db.Queryable<UserInfo>()
.Where(u =>
u.Index.Contains(searchKeyword) ||
u.Username.Contains(searchKeyword) ||
u.Email.Contains(searchKeyword) ||
u.Region.Contains(searchKeyword) ||
u.Phonenumber.Contains(searchKeyword)
)
.ToList();
us_Datagrid.ItemsSource = users;
MessageBox.Show($"共找到 {users.Count} 条匹配记录", "搜索结果",MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show($"搜索失败: {ex.Message}", "错误",MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
运行画面如下所示
6.2 增加功能
通过在文本框输入内容之后,点击按钮增加即可,按钮逻辑,附果糖网链接,插入 、插入 教程、新增数据 、添加数据 - SqlSugar 5x - .NET果糖网
private void Add_Click(object sender, RoutedEventArgs e)
{
try
{
var newUser = new UserInfo
{
Index = Id_Text.Text,
Username = UserName_Text.Text,
Age = int.Parse(Age_Text.Text),
Email = Email_Text.Text,
Region = Region_Text.Text,
Phonenumber = PhoneNumber_Text.Text,
CreateTime = DateTime.Now
};
var db = SqliteDbHelper.Db;
db.Insertable(newUser).ExecuteCommand();
MessageBox.Show("用户添加成功", "成功",MessageBoxButton.OK, MessageBoxImage.Information);
LoadUserData();
}
catch (Exception ex)
{
MessageBox.Show($"添加用户失败: {ex.Message}", "错误",MessageBoxButton.OK, MessageBoxImage.Error);
}
}
实现效果
6.3 删除功能
通过选中datagrid的当前行后点击删除按钮就行删除操作,附果糖网官方链接 普通删除 、单表删除、表达式删除 用法 - SqlSugar 5x - .NET果糖网
private void Remove_Click(object sender, RoutedEventArgs e)
{
// 获取选中的用户
var selectedUser = us_Datagrid.SelectedItem as UserInfo;
if (selectedUser == null)
{
MessageBox.Show("请先选择要删除的用户", "提示",MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
// 确认删除
if (MessageBox.Show($"确定要删除用户 '{selectedUser.Username}' 吗?", "确认删除", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes)
{
return;
}
try
{
var db = SqliteDbHelper.Db;
// 执行删除
int affectedRows = db.Deleteable(selectedUser).ExecuteCommand();
if (affectedRows > 0)
{
MessageBox.Show("用户删除成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
LoadUserData(); // 重新加载数据
}
else
{
MessageBox.Show("用户删除失败,可能已被其他操作删除", "错误",MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex)
{
MessageBox.Show($"删除用户失败: {ex.Message}", "错误",MessageBoxButton.OK, MessageBoxImage.Error);
}
}
运行效果
6.4 更改功能
通过选中按钮来对当前行进行修改,单表更新、更新数据 - SqlSugar 5x - .NET果糖网
private void Change_Click(object sender, RoutedEventArgs e)
{
// 获取选中的用户
var selectedUser = us_Datagrid.SelectedItem as UserInfo;
if (selectedUser == null)
{
MessageBox.Show("请先选择要修改的用户", "提示",MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
try
{
// 更新用户信息
selectedUser.Index = Id_Text.Text;
selectedUser.Username = UserName_Text.Text;
selectedUser.Age = int.Parse(Age_Text.Text);
selectedUser.Email = Email_Text.Text;
selectedUser.Region = Region_Text.Text;
selectedUser.Phonenumber = PhoneNumber_Text.Text;
selectedUser.CreateTime = DateTime.Now;
var db = SqliteDbHelper.Db;
// 执行更新
int affectedRows = db.Updateable(selectedUser).ExecuteCommand();
if (affectedRows > 0)
{
MessageBox.Show("用户信息修改成功", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
LoadUserData(); // 重新加载数据
}
else
{
MessageBox.Show("用户信息修改失败,数据未变更", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex)
{
MessageBox.Show($"修改用户失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
运行效果
6.5 查询功能
使用了模糊匹配查询的功能,匹配到相同的字段就会展示出来,简单的 查询 - SqlSugar 5x - .NET果糖网
private void Search_Click(object sender, RoutedEventArgs e)
{
string searchKeyword = Search_Text.Text.Trim();
if (string.IsNullOrEmpty(searchKeyword))
{
// 无搜索关键词时显示全部数据
LoadUserData();
return;
}
try
{
var db = SqliteDbHelper.Db;
// 多字段模糊查询(Index、Username、Email、Region、Phonenumber)
var users = db.Queryable<UserInfo>()
.Where(u =>
u.Index.Contains(searchKeyword) ||
u.Username.Contains(searchKeyword) ||
u.Email.Contains(searchKeyword) ||
u.Region.Contains(searchKeyword) ||
u.Phonenumber.Contains(searchKeyword)
)
.ToList();
us_Datagrid.ItemsSource = users;
MessageBox.Show($"共找到 {users.Count} 条匹配记录", "搜索结果",MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (Exception ex)
{
MessageBox.Show($"搜索失败: {ex.Message}", "错误",MessageBoxButton.OK, MessageBoxImage.Error);
}
}