Dapper(三) 基本增删改查

1. 首先实例化连接对象.

        MysqlHelper _db = new MysqlHelper();

2.添加

using (IDbConnection conn = _db.GetMySqlConnection())
            {
                string sqlStr = @"insert into 表
                                        (字段1,字段2) 
                                  values
                                        (@实体字段1,@实体字段2)";
                return conn.Execute(sqlStr, 实体);
            }

2.编辑

using (IDbConnection conn = _db.GetMySqlConnection())
            {
                string sqlStr = @"update 表
                                    set 字段1=@实体字段1,字段2=@实体字段2 
                                    where id=@id ";
                return conn.Execute(sqlStr, 实体);
            }

3.删除

using (IDbConnection conn = _db.GetMySqlConnection())
            {
                var model = new { id= id};
                string sqlStr = @"delete from 表
                                    where id =@id";
                return conn.Execute(sqlStr,model);
            }

4.查询

using (IDbConnection conn = _db.GetMySqlConnection())
            {
                string sqlCommandStr = @"SELECT 
                                            字段
                                        FROM 表  
                                        WHERE id=@id";
                return conn.Query<实体>(sqlCommandStr, 实体).FirstOrDefault();
            }

5.分页查询列表

using (IDbConnection conn = _db.GetMySqlConnection())
            {
                var model = new
                {
                   
                    offset = (page - 1) * pagesize,//起始位置=(页码-1)*页页大小
                    pagesize = pagesize,//页大小
                    
                };
                string sqlCommandStr = @"SELECT 字段 
                                            FROM 表 where 1=1";
               
                
                sqlCommandStr += " ORDER BY id LIMIT @offset, @pagesize";
               
                return conn.Query<返回值实体>(sqlCommandStr, 实体).ToList();
            }

 

你可能感兴趣的:(SQL,Dapper基本应用)