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咱們能夠拿到數據庫中全部的用戶信息

 

 歡迎指正

相關文章
相關標籤/搜索