连接mysql

1.nuget  所搜MySql.Data

2.appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "server=127.0.0.1;userid=root;password=Rock3690;database=webreading;"
  },
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  }
}

3.

Startup.cs 添加一行

services.Add(new ServiceDescriptor(typeof(UserContext), new UserContext(Configuration.GetConnectionString("DefaultConnection"))));

4.

新建model类  UsersModel.cs

    public class UsersModel
    {
        public int id { get; set; }
        public string Users { get; set; }
        public string PassWord { get; set; }
    }

5.

新建context类  UserContext

using MySql.Data.MySqlClient;
using System.Collections.Generic;
using WebReading.Models;

namespace WebReading.Context
{
    public class UserContext
    {
        public string ConnectionString { get; set; }
        public UserContext(string connectionString)
        {
            this.ConnectionString = connectionString;
        }
        private MySqlConnection GetConnection()
        {
            return new MySqlConnection(ConnectionString);
        }

        public List<UsersModel> GetAllUser()
        {
            List<UsersModel> list = new List<UsersModel>();
            //连接数据库
            using (MySqlConnection conn = GetConnection())
            {
                conn.Open();
                //查找数据库里面的表
                MySqlCommand cmd = new MySqlCommand("select id,users,password from t_login", conn);
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    //读取数据
                    while (reader.Read())
                    {
                        list.Add(new UsersModel()
                        {
                            id = reader.GetInt32("id"),
                            Users = reader.GetString("users"),
                            PassWord = reader.GetString("password")
                        });
                    }
                }
            }
            return list;
        }
    }
}

6.

Controller  添加 Action

        [HttpPost]
        public IActionResult Home()
        {
            UserContext context = HttpContext.RequestServices.GetService(typeof(UserContext)) as UserContext;
            var data = context.GetAllUser();
            return View(data);
        }
原文地址:https://www.cnblogs.com/buchizaodian/p/9569687.html