1. 程式人生 > >Dapper連線MySql資料庫

Dapper連線MySql資料庫

首先通過NuGet在專案中分別安裝Dapper和MySql.Data的引用

PM> Install-Package Dapper -Version 1.40.0
PM> Install-Package MySql.Data -Version 6.7.9

 Web.config

 <connectionStrings>
    <add name="MySqlConnectionString" connectionString="Database=mysql_test;Data Source=localhost;User Id=root;Password=123456;CharSet=utf8;port=3306
" /> </connectionStrings>

 封裝一下Dapper 

public class DapperService
{
        public static MySqlConnection MySqlConnection()
        {
            string mysqlConnectionString = ConfigurationManager.ConnectionStrings["MySqlConnectionString"].ToString();
            var connection = new
MySqlConnection(mysqlConnectionString); connection.Open(); return connection; } }

 MySql資料庫

 User實體

public class User
{
        public int ID { get; set; }

        public string Name { get; set; }

        public bool Sex { get; set; }

        
public decimal Age { get; set; } public string Tel { get; set; } public DateTime? ModifyTime { get; set; } }

 Select查詢

using (IDbConnection conn = DapperService.MySqlConnection())
{
          string sqlCommandStr = @"SELECT * FROM USER";
          List<User> userList = conn.Query<User>(sqlCommandStr).ToList();
          return View(userList);
}

  Insert插入

public void InsertInfo(User user)
{
     string insertSqlStr = @"INSERT INTO  user(Name,Sex,Age,Tel)VALUES(@Name,@Sex,@Age,@Tel)";

     using (IDbConnection conn = DapperService.MySqlConnection())
     {
      // conn.Execute(insertSqlStr, new { Name="ssss",Sex=true,Age="22",Tel="2222"});  ///這種是手動賦值
          conn.Execute(insertSqlStr, user);    //這種是按實體插入
     }
}