Dapper连接MySql

Web.config

 <connectionStrings>
    <add name="MsConnectionStr" 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 mysqlConnectionStr = ConfigurationManager.ConnectionStrings["MsConnectionStr"].ToString();
            var connection = new MySqlConnection(mysqlConnectionStr);
            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 userList = conn.Query(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);    //这种是按实体插入
     }
}

 

转载于:https://www.cnblogs.com/xinyibufang/p/8668153.html

你可能感兴趣的:(Dapper连接MySql)