先创建一个一个项目,具体就不详细说了,请参见本人第一篇文章同一个项目写下来的哦
使用NuGet引用MySql.Data插件
然后修改你的appsettings.json文件
{
"ConnectionStrings": {
"DefaultConnection": "server=127.0.0.1;userid=root;password=123456;database=viewdata;"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Warning"
}
}
}
如果连接字符串不正确后面运行时会报错哦,Option not supported异常或者其他异常
然后创建链接数据库的类直接上代码
using MySql.Data.MySqlClient;
using NetCore.DTO;
using System;
using System.Collections.Generic;
using System.Text;
namespace Library
{
public class UserContext
{
public string ConnectionString { get; set; }
public UserContext(string connectionString)
{
this.ConnectionString = connectionString;
}
private MySqlConnection GetConnection()
{
return new MySqlConnection(ConnectionString);
}
public List<userDto> GetAllUser()
{
List<userDto> list = new List<userDto>();
//连接数据库
using (MySqlConnection msconnection = GetConnection())
{
msconnection.Open();
//查找数据库里面的表
MySqlCommand mscommand = new MySqlCommand("select host,user,authentication_string from user", msconnection);
using (MySqlDataReader reader = mscommand.ExecuteReader())
{
//读取数据
while (reader.Read())
{
list.Add(new userDto()
{
host = reader.GetString("host"),
user = reader.GetString("user"),
authentication_string = reader.GetString("authentication_string")
});
}
}
}
return list;
}
}
}
下一步就是修改你Startup 中的ConfigureServices,添加下面的代码如图
services.Add(new ServiceDescriptor(typeof(UserContext), new UserContext(Configuration.GetConnectionString("DefaultConnection"))));
最后一步就是在控制器中调用了
查看结果