要在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窗体中调用相应的方法来实现数据库操作。