Dapper简单封装

NuGet安装Dapper,数据库SQL Server,工具类源码下载

1、执行sql

public int Execute(string sql, object para = null) {
            int rows = 0;
            using (IDbConnection conn = new SqlConnection(ConnStr)) {
                try {
                    conn.Open();
                    rows = conn.Execute(sql, para);
                }
                catch (Exception ex) {
                    //throw ex;
                }
                finally {
                    conn.Close();
                }
            }
            return rows;
        }

2、插入记录,返回自增id

public int Insert(string sql, object para) {
            int id = 0;
            using (IDbConnection conn = new SqlConnection(ConnStr)) {
                try {
                    conn.Open();
                    id = conn.QueryFirstOrDefault(sql + ";SELECT CAST(SCOPE_IDENTITY() as int);", para);

                }
                catch (Exception ex) {
                    //throw ex;
                }
                finally {
                    conn.Close();
                }
            }
            return id;
        }

3、查询sql

public dynamic Query(string sql, object para = null) {
            dynamic d = null;
            using (IDbConnection conn = new SqlConnection(ConnStr)) {
                try {
                    conn.Open();
                    d = conn.Query(sql, para);
                }
                catch (Exception ex) {
                    //throw ex;
                }
                finally {
                    conn.Close();
                }
            }
            return d;
        }

4、事务

public bool ExecuteTran() {            
bool f = false;
            using (IDbConnection conn = new SqlConnection(ConnStr)) {
                try {
                    conn.Open();
                    IDbTransaction tran = conn.BeginTransaction();
                    try {

                        for (int i = 0; i < _command.Count; i++) {
                            conn.Execute(_command[i].CommandText, _command[i].Parameter, tran);
                        }
                        tran.Commit();
                        _command.Clear();
                        f = true;
                    }
                    catch (Exception ex) {
                        tran.Rollback();
                        throw ex;
                    }
                }
                catch (Exception ex) {
                    //throw ex;
                }
                finally {
                    conn.Close();
                }
            }
            return f;
        }

工具类源码下载

 

 

 

你可能感兴趣的:(Dapper简单封装)