How to connect to a MySQL Data Source in Visual Studio

前端 未结 11 2100
忘了有多久
忘了有多久 2020-11-28 09:15

I use the MySQL Connector/Net to connect to my database by referencing the assembly (MySql.Data.dll) and passing in a connection string to MySqlConnection. I

11条回答
  •  渐次进展
    2020-11-28 09:40

    Right Click the Project in Solution Explorer and click Manage NuGet Packages

    Search for MySql.Data package, when you find it click on Install

    Here is the sample controller which connects to MySql database using the mysql package. We mainly make use of MySqlConnection connection object.

     public class HomeController : Controller
    {
        public ActionResult Index()
        {
            List employees = new List();
            string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            using (MySqlConnection con = new MySqlConnection(constr))
            {
                string query = "SELECT EmployeeId, Name, Country FROM Employees";
                using (MySqlCommand cmd = new MySqlCommand(query))
                {
                    cmd.Connection = con;
                   con.Open();
                    using (MySqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            employees.Add(new EmployeeModel
                            {
                                EmployeeId = Convert.ToInt32(sdr["EmployeeId"]),
                                Name = sdr["Name"].ToString(),
                                Country = sdr["Country"].ToString()
                            });
                        }
                    }
                    con.Close();
                }
            }
    
            return View(employees);
        }
    }
    

提交回复
热议问题