sqlsugar帮助类
时间: 2024-02-18 15:58:06 浏览: 34
SqlSugar是一个由国内开发者开发的C# ORM框架,它提供了一系列的帮助类来简化数据库操作。下面是一个使用SqlSugar帮助类的示例:
```csharp
using SqlSugar;
public class DBHelper
{
private static string connectionString = "your_connection_string";
public static SqlSugarClient GetInstance()
{
var db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = connectionString,
DbType = DbType.SqlServer, // 根据实际情况选择数据库类型
IsAutoCloseConnection = true, // 自动关闭数据库连接
InitKeyType = InitKeyType.Attribute // 使用属性名作为表的主键
});
return db;
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
public class UserRepository
{
public List<User> GetAllUsers()
{
using (var db = DBHelper.GetInstance())
{
var userList = db.Queryable<User>().ToList();
return userList;
}
}
public User GetUserById(int id)
{
using (var db = DBHelper.GetInstance())
{
var user = db.Queryable<User>().InSingle(id);
return user;
}
}
public void AddUser(User user)
{
using (var db = DBHelper.GetInstance())
{
db.Insertable(user).ExecuteCommand();
}
}
public void UpdateUser(User user)
{
using (var db = DBHelper.GetInstance())
{
db.Updateable(user).ExecuteCommand();
}
}
public void DeleteUser(int id)
{
using (var db = DBHelper.GetInstance())
{
db.Deleteable<User>().In(id).ExecuteCommand();
}
}
}
```
上述代码中,`DBHelper`类是一个帮助类,用于获取SqlSugarClient实例,其中`connectionString`需要替换为你的数据库连接字符串。`User`类是一个实体类,用于映射数据库表。`UserRepository`类是一个数据访问类,封装了对用户表的增删改查操作。
你可以根据实际需求,使用SqlSugar提供的各种方法来进行数据库操作,例如查询所有用户、根据ID查询用户、添加用户、更新用户和删除用户等。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)