首先,您必须向API添加一个控制器或创建一个端点,如下所示:
// here is only the endpoint
[HttpGet]
[Route("dbcheck")]
public IActionResult DbConnect() {
return Ok();
}
然后从NuGet添加MySqlConnection
string connectionString = "";
MySqlConnection connection = new MySqlConnection(connectionString)
正如您所看到的,您必须定义一个字符串(connectionString)。
对于这个字符串的内容,我添加了以下接口来读取appsettings.json中的设置。(见下文,我稍后展示)
private readonly IConfiguration Configuration;
public NameOfTheController(IConfiguration configuration) {
Configuration = configuration;
}
现在可以这样使用它了,您还可以看到第一个SQL命令:
string connectionString = Configuration["ConnectionStrings:essenskasse"] ?? "";
MySqlConnection connection = new MySqlConnection(connectionString)
MySqlCommand command = new MySqlCommand("SELECT * FROM Test", con);
在此之后,可以建立连接。
要执行该命令,请使用MySqlDataReader,并将读取器的结果填写在DataTable中:
connection.Open();
MySqlDataReader reader = command.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(reader);
reader.Close();
connection.Close();
别忘了
联系关
最后!
这是一个完整的演示控制器:
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using System.Data;
namespace API.Controllers {
[Route("api/[controller]")]
[ApiController]
public class DemoController : ControllerBase {
private readonly IConfiguration Configuration;
public DemoController(IConfiguration configuration) {
Configuration = configuration;
}
[HttpGet, Route("dbcheck")]
public IActionResult DbConnect() {
try {
MySqlConnection connection = new MySqlConnection(Configuration["ConnectionStrings:mysql"]);
MySqlCommand command = new MySqlCommand("SELECT * FROM Test", connection);
connection.Open();
MySqlDataReader reader = command.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(reader);
reader.Close();
connection.Close();
return Ok();
}
catch (Exception ex) {
return BadRequest(ex.ToString());
}
}
}
}
下面是API的appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"mysql": "Server=database;Port=3306;Uid=user;Pwd=secretpassword;Database=db;SslMode=None;"
}
}
SslMode=无
之所以使用,是因为:
https://stackoverflow.com/a/78042591
您也不能在docker上下文中连接到localhost:3306。
相反,您应该使用服务名称,您的名称是数据库,所以我插入了它。