如何在Winform中使用SqlSugar進(jìn)行數(shù)據(jù)庫(kù)操作

sql
小樊
204
2024-08-16 16:48:42
欄目: 云計(jì)算

要在Winform中使用SqlSugar進(jìn)行數(shù)據(jù)庫(kù)操作,可以按照以下步驟進(jìn)行:

  1. 首先,在Visual Studio中創(chuàng)建一個(gè)Winform應(yīng)用程序項(xiàng)目。

  2. 在項(xiàng)目中引入SqlSugar的NuGet包。可以在NuGet包管理器中搜索SqlSugar并安裝。

  3. 在項(xiàng)目中創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)連接字符串,用于連接數(shù)據(jù)庫(kù)??梢栽贏pp.config文件中添加如下節(jié)點(diǎn):

<connectionStrings>
    <add name="MyConnection" connectionString="Server=YourServer;Database=YourDatabase;User Id=YourUsername;Password=YourPassword;" providerName="System.Data.SqlClient" />
</connectionStrings>
  1. 創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)操作類,用于執(zhí)行數(shù)據(jù)庫(kù)操作。可以參考以下示例代碼:
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;

public class DatabaseHelper
{
    private static string connectionString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
    private static SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
    {
        ConnectionString = connectionString,
        DbType = DbType.SqlServer,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute
    });

    public static List<User> GetAllUsers()
    {
        return db.Queryable<User>().ToList();
    }

    public static void AddUser(User user)
    {
        db.Insertable(user).ExecuteCommand();
    }

    public static void UpdateUser(User user)
    {
        db.Updateable(user).ExecuteCommand();
    }

    public static void DeleteUser(int userId)
    {
        db.Deleteable<User>().In(userId).ExecuteCommand();
    }
}
  1. 在Winform窗體中調(diào)用數(shù)據(jù)庫(kù)操作類的方法進(jìn)行數(shù)據(jù)庫(kù)操作。可以參考以下示例代碼:
private void Form1_Load(object sender, EventArgs e)
{
    List<User> users = DatabaseHelper.GetAllUsers();
    dataGridView1.DataSource = users;
}

private void btnAdd_Click(object sender, EventArgs e)
{
    User user = new User
    {
        UserName = txtUserName.Text,
        Age = Convert.ToInt32(txtAge.Text)
    };
    DatabaseHelper.AddUser(user);
    MessageBox.Show("User added successfully!");
}

private void btnUpdate_Click(object sender, EventArgs e)
{
    User user = new User
    {
        UserId = Convert.ToInt32(txtUserId.Text),
        UserName = txtUserName.Text,
        Age = Convert.ToInt32(txtAge.Text)
    };
    DatabaseHelper.UpdateUser(user);
    MessageBox.Show("User updated successfully!");
}

private void btnDelete_Click(object sender, EventArgs e)
{
    int userId = Convert.ToInt32(txtUserId.Text);
    DatabaseHelper.DeleteUser(userId);
    MessageBox.Show("User deleted successfully!");
}

通過(guò)以上步驟,您就可以在Winform應(yīng)用程序中使用SqlSugar進(jìn)行數(shù)據(jù)庫(kù)操作了。在實(shí)際項(xiàng)目中,您可以根據(jù)具體需求擴(kuò)展數(shù)據(jù)庫(kù)操作類,并在Winform窗體中調(diào)用相應(yīng)的方法來(lái)實(shí)現(xiàn)數(shù)據(jù)庫(kù)操作。

0