要在Winform中使用SqlSugar進行數據庫操作,可以按照以下步驟進行:
首先,在Visual Studio中創建一個Winform應用程序項目。
在項目中引入SqlSugar的NuGet包。可以在NuGet包管理器中搜索SqlSugar并安裝。
在項目中創建一個數據庫連接字符串,用于連接數據庫。可以在App.config文件中添加如下節點:
<connectionStrings>
<add name="MyConnection" connectionString="Server=YourServer;Database=YourDatabase;User Id=YourUsername;Password=YourPassword;" providerName="System.Data.SqlClient" />
</connectionStrings>
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();
}
}
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!");
}
通過以上步驟,您就可以在Winform應用程序中使用SqlSugar進行數據庫操作了。在實際項目中,您可以根據具體需求擴展數據庫操作類,并在Winform窗體中調用相應的方法來實現數據庫操作。