Asp.Net Core连接Mysql数据库

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

添加nuget包  Mysql.Datasql

2、新建一个UserContext类数据库

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

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

 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;
        }

    }

3、在StartUp.cs中注入UserContextthis

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

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

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

  

4、在配置文件中插入连接字符串对象

5、启动程序blog

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

经过上面写的sql咱们能够拿到数据库中全部的用户信息

 

 欢迎指正

相关文章
相关标签/搜索