Asp.Net Core链接Mysql数据库

一、新建一个Asp.Net Core WebMVC程序

添加nuget包  Mysql.Data

二、新建一个UserContext类

下面代码中的UserInfo是我自己建的一个实体,里面有俩字段:host和name.数据类型都是string

MysqlConnection 和MysqlCommand在MySql.Data.MySqlClient命名空间下;

 public class UserContext
    {
        public string ConnectionString { get; set; }

        //实例化时获得MYSQLl链接字符串
        public UserContext(string connectionString)
        {
            this.ConnectionString = connectionString;
        }

        /// <summary>
        /// MySqlConnection 是ADO.NET中Connection对象的Mysql版本
        /// 这里是通过读取appsetting.json中的链接字符串打开一个mysql的链接
        /// </summary>
        /// <returns></returns>
        private MySqlConnection GetConnection()
        {

            return new MySqlConnection(ConnectionString);
        }

        public List<UserInfo> GetAllUser()
        {
            List<UserInfo> list = new List<UserInfo>();
            ///通过connection对象打开一个链接管道
            using (MySqlConnection connection = GetConnection())
            {
                //打开管道
                connection.Open();
                //MySqlCommand是ADO.NET Command对象的mysql版本,这里是声明一个操作对象来执行SQL
                MySqlCommand comand = new MySqlCommand("select host,user from mysql.user", connection);
                //使用Reader对象对上面SQL执行的返回结果进行读取
                using (MySqlDataReader reader = comand.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        list.Add(new UserInfo { Host = reader.GetString("host") });
                    }
                }
            }
            return list;
        }

    }

三、在StartUp.cs中注入UserContext

Dev是一个我在appsetting.json配置文件中的一个节点,下面会写。

用Configuration.GetConnectionString会自动读取配置文件的ConnectionStrings节点

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

  

四、在配置文件中插入链接字符串

五、启动程序

在HomeController中获取一下上面写的数据

通过上面写的sql我们可以拿到数据库中所有的用户信息

 欢迎指正

原文地址:https://www.cnblogs.com/Tassdar/p/9996415.html