一、新建一個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我們可以拿到數據庫中所有的用戶信息
歡迎指正