SqlSugar
原创大约 1 分钟约 425 字
1. 添加 Nuget 包
Install-Package SqlSugar
Install-Package Newtonsoft.Json
Install-Package MySql.Data
2. 基础使用
2.1. 配置
public class UtiDbConn
{
public static SqlSugarClient GetDbConnection()
{
// 我的主机IP地址
string strServer = "127.0.0.1";
// 我创建的数据库
string strDataBase = "api";
// 数据库登录账号
string strUid = "root";
// 数据库登录密码
string strPwd = "root";
//创建数据库对象 (用法和EF Dappper一样通过new保证线程安全)
SqlSugarClient Db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = $"server={strServer};uid={strUid};pwd={strPwd};database={strDataBase}",
DbType = SqlSugar.DbType.MySql,
InitKeyType = InitKeyType.Attribute, //从实体特性中读取主键自增列信息
IsAutoCloseConnection = true //自动释放连接池, 写代码就不需要考虑 open close
});
return Db;
}
}
2.2. 定义数据对象
private readonly SqlSugarClient db = UtiDbConn.GetDbConnection();
2.3. 创建实体类
[SugarTable("tbEmployee")]
public partial class tbEmployee
{
public tbEmployee()
{
}
/// <summary>
/// Desc:
/// Default:
/// Nullable:False
/// </summary>
public string Name { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:False
/// </summary>
public int Age { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:False
/// </summary>
public string Address { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:False
/// </summary>
public string EmployeeNumber { get; set; }
/// <summary>
/// Desc:
/// Default:
/// Nullable:False
/// </summary>
public DateTime OnboardingTime { get; set; }
}
2.4. 生成数据库实体类
var db = UtiDbConn.GetDbConnection();
// 参数1代表存放位置 参数2代表命名空间
db.DbFirst.IsCreateAttribute().CreateClassFile(@"D:\code\DevelopApplication\Winfrom", "WindowsFormsApp3");
2.5. 执行插入操作
var result = db.Insertable(new tbEmployee()
{
Name = "ab",
Address = "ad",
Age = 10,
EmployeeNumber = "100",
OnboardingTime = new DateTime()
}).ExecuteCommand();
2.6. 初始化表结构
db.CodeFirst.InitTables(typeof(YourEntity));
2.7. 检查连接状态
var sqlConnection = db.Ado.Connection as SqlConnection; // 获取底层的SqlConnection对象
if (sqlConnection != null && sqlConnection.State == ConnectionState.Open)
{
Console.WriteLine("连接是打开的");
}
else
{
Console.WriteLine("连接未打开");
}