.NET Core Web Api mysql配置sqlsugar连接池
时间: 2024-01-19 15:06:04 浏览: 173
要在.NET Core Web Api中配置SQLSugar连接池,您可以按照以下步骤进行操作:
1. 在您的.NET Core Web Api项目中安装SQLSugar和MySql.Data包。
2. 在appsettings.json文件中添加MySQL数据库连接字符串,如下所示:
```json
{
"ConnectionStrings": {
"DefaultConnection": "server=localhost;database=your_database;user=root;password=your_password;pooling=true;"
}
}
```
3. 创建一个名为SugarDao.cs的文件,并在其中添加以下代码:
```csharp
using Microsoft.Extensions.Configuration;
using MySql.Data.MySqlClient;
using SqlSugar;
using System;
namespace YourNamespace
{
public class SugarDao
{
private readonly IConfiguration _configuration;
private readonly MySqlConnection _connection;
public SugarDao(IConfiguration configuration)
{
_configuration = configuration;
var connectionString = _configuration.GetConnectionString("DefaultConnection");
_connection = new MySqlConnection(connectionString);
}
public SqlSugarClient GetInstance()
{
var db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = _configuration.GetConnectionString("DefaultConnection"),
DbType = DbType.MySql,
IsAutoCloseConnection = true,
InitKeyType = InitKeyType.Attribute,
ConfigureExternalServices = new ConfigureExternalServices()
{
DataInfoCacheService = new HttpRuntimeCache()
},
MoreSettings = new ConnMoreSettings()
{
IsAutoRemoveDataCache = true
},
AopEvents = new AopEvents
{
OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(sql + "\r\n" +
_connection.CreateCommand().AppendParameters(pars).CommandText);
Console.WriteLine();
}
}
});
db.Ado.ExecuteCommand("SET NAMES utf8mb4;");
return db;
}
}
}
```
4. 在Startup.cs文件中的ConfigureServices方法中添加以下代码:
```csharp
services.AddSingleton<SugarDao>();
services.AddScoped<ISqlSugarClient>(i => i.GetService<SugarDao>().GetInstance());
```
5. 现在您可以在您的控制器中注入ISqlSugarClient,如下所示:
```csharp
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
namespace YourNamespace.Controllers
{
[ApiController]
[Route("[controller]")]
public class YourController : ControllerBase
{
private readonly ISqlSugarClient _db;
public YourController(ISqlSugarClient db)
{
_db = db;
}
[HttpGet]
public IActionResult Get()
{
var data = _db.Queryable<YourModel>().ToList();
return Ok(data);
}
}
}
```
这样,您就完成了在.NET Core Web Api中配置SQLSugar连接池的操作。
阅读全文