# MVC5 Asp.Net MySQL Connection 手動連線MySQL資料庫 1. 到phpMyAdmin -> 創建MySQL資料表 ![](https://i.imgur.com/6nM68g3.png) 2. 工具: visual studio 2019 ![](https://i.imgur.com/iSWP4Ab.png) ![](https://i.imgur.com/UOOc2wc.png) NuGet->MySql.Data(6.10.8) ![](https://i.imgur.com/xaSQlJC.png) ![](https://i.imgur.com/xsx719L.png) 3.專案 ![](https://i.imgur.com/Tme429R.png) ```haskell= namespace WebApplication2.Models { public class MysqlClass { public string Firstname { get; set; } public string Lastname { get; set; } public string City { get; set; } } } ``` Controllers Files->Add Controller (MySQLController.cs) ```haskell= namespace WebApplication2.Controllers { public class MySQLController : Controller { // GET: MySQL public ActionResult Index() { List<MysqlClass> list1 = new List<MysqlClass>(); //Mysqlconnection ->必須與Web.config name相同 string mainconn = ConfigurationManager.ConnectionStrings["Mysqlconnection"].ConnectionString; MySqlConnection mysql = new MySqlConnection(mainconn); string query = "select * from Employee"; MySqlCommand comm = new MySqlCommand(query); comm.Connection = mysql; mysql.Open(); MySqlDataReader dr = comm.ExecuteReader(); while (dr.Read()) { list1.Add(new MysqlClass { Firstname = dr["Firstname"].ToString(), Lastname = dr["Lastname"].ToString(), City = dr["City"].ToString(), }); } mysql.Close(); return View(list1); } } } ``` * MySQLController 中的語法public ActionResult Index()裡面->右鍵 新增檢視->MVC5檢視->![](https://i.imgur.com/aMuP0lW.png) ->加入->產生->View->MySQL->Index.cshtmL ```htmlembedded= @model IEnumerable<WebApplication2.Models.MysqlClass> @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <table> <tr> <th>FistName</th> <th>LastName</th> <th>City</th> </tr> @foreach (WebApplication2.Models.MysqlClass d in Model) { <tr> <td>@d.Firstname</td> <td>@d.Lastname</td> <td>@d.City</td> </tr> } </table> </body> </html> ``` Web.config ```haskell= /*name 與MySQLController中的 string mainconn = ConfigurationManager.ConnectionStrings["Mysqlconnection"].ConnectionString;*/ <connectionStrings> <add name="Mysqlconnection" connectionString="server=127.0.0.1;User Id=root;Persist Security Info=True;database=employee;CHARSET=big5" providerName="MySql.Data.MySqlClient"/> </connectionStrings> ``` 成功連接資料庫 ![](https://i.imgur.com/7V0Zsg2.png) ###### tags: `C#` `MVC5` `Asp.Net` `MySQL`