ADO.NET操作PostgreSQL:数据库操作类(已封装)

1.增、删、改通用方法

        /// 
        /// 增、删、改通用方法
        /// 
        /// Command对象的CommandText属性(sql语句或存储过程名称)
        /// Command对象的Parameters属性(sql语句或存储过程参数)
        /// 
        public static int ExecuteNonQuery(string commandText, NpgsqlParameter[] commandParameters)
        {
            using (NpgsqlConnection conn = new NpgsqlConnection(datalink.PsconnectionString))
            {
                using (NpgsqlCommand cmd = new NpgsqlCommand(commandText, conn))
                {
                    cmd.Parameters.AddRange(commandParameters);
                    conn.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }

 

2.读取1行记录

 

        /// 
        /// 读取1行记录
        /// 
        /// 结果集对应的Model
        /// 读取结果集的SqlDataReader
        /// Command对象的CommandText属性(sql语句或存储过程名称)
        /// Command对象的Parameters属性(sql语句或存储过程参数)
        /// 
        public static T ExecuteReader(Func Reader, string commandText, NpgsqlParameter[] commandParameters)
        {
            T entity = default(T);
            using (NpgsqlConnection conn = new NpgsqlConnection(datalink.PsconnectionString))
            {
                using (NpgsqlCommand cmd = new NpgsqlCommand(commandText, conn))
                {
                    cmd.Parameters.AddRange(commandParameters);
                    conn.Open();
                    using (NpgsqlDataReader sr = cmd.ExecuteReader())
                    {
                        while (sr.Read())
                        {
                            entity = Reader(sr);
                        }
                    }
                }
            }
            return entity;
        }

 

3.读取n行记录

 

        /// 
        /// 读取n行记录
        /// 
        /// 结果集对应的Model
        /// 读取结果集的SqlDataReader
        /// Command对象的CommandText属性(sql语句或存储过程名称)
        /// Command对象的Parameters属性(sql语句或存储过程参数)
        /// 
        public static List ExecuteReaderList(Func Reader, string commandText, NpgsqlParameter[] commandParameters)
        {
            List list = new List();
            using (NpgsqlConnection conn = new NpgsqlConnection(datalink.PsconnectionString))
            {
                using (NpgsqlCommand cmd = new NpgsqlCommand(commandText, conn))
                {
                    cmd.Parameters.AddRange(commandParameters);
                    conn.Open();
                    using (NpgsqlDataReader sr = cmd.ExecuteReader())
                    {
                        while (sr.Read())
                        {
                            list.Add(Reader(sr));
                        }
                    }
                }
            }
            return list;
        }

 

4.读取第1行第1列记录

 

        /// 
        /// 读取第1行第1列记录
        /// 
        /// Command对象的CommandText属性(sql语句或存储过程名称)
        /// Command对象的Parameters属性(sql语句或存储过程参数)
        /// 
        public static object ExecuteScalar(string commandText, NpgsqlParameter[] commandParameters)
        {
            using (NpgsqlConnection conn = new NpgsqlConnection(datalink.PsconnectionString))
            {
                using (NpgsqlCommand cmd = new NpgsqlCommand(commandText, conn))
                {
                    cmd.Parameters.AddRange(commandParameters);
                    conn.Open();
                    return cmd.ExecuteScalar();
                }
            }
        }

 

5.分页查询

 

        /// 
        /// 分页查询
        /// 
        /// 结果集对应的Model
        /// 读取结果集的DataReader
        /// 数据表名称
        /// 查询条件
        /// 排序字段名称
        /// 排序方式
        /// 页码
        /// 每页的数据量
        /// 
        public static PagedData SearchPagedList(Func Reader, string table, string sidx, string sord, int page, int rows, string limitation)
        {
            PagedData result = new PagedData { PageIndex = page, PageSize = rows };

            string sql = "select * from \"" + table + "\" where " + limitation + " order by \"" + sidx + "\"" + " " + sord + " limit @PageSize offset (@PageIndex -1) * @PageSize;";
            sql += "select cast(count(*) as integer) from \"" + table + "\" where " + limitation;

            using (NpgsqlConnection conn = new NpgsqlConnection(postgresqlconn.connectionString))
            {
                using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn))
                {
                    cmd.Parameters.Add("@PageIndex", NpgsqlDbType.Integer).Value = page;
                    cmd.Parameters.Add("@PageSize", NpgsqlDbType.Integer).Value = rows;
                    conn.Open();
                    using (NpgsqlDataReader sr = cmd.ExecuteReader())
                    {
                        result.DataList = new List();
                        while (sr.Read())
                        {
                            result.DataList.Add(Reader(sr));
                        }
                        bool bln = sr.NextResult();
                        while (sr.Read())
                        {
                            result.DataCount = (int)sr[0];
                            result.PageCount = result.DataCount % result.PageSize == 0 ? result.DataCount / result.PageSize : result.DataCount / result.PageSize + 1;
                        }
                    }
                }
            }
            return result;
        }

 

6.执行事务

 

        /// 
        /// 执行事务
        /// 
        /// Command参数对象列表
        /// 如果事务提交,返回受影响行数;如果事务回滚,返回异常信息。
        /// 
        public static bool ExecuteTransaction(List commandModel, out string message)
        {
            message = string.Empty;
            int rows = 0;
            using (NpgsqlConnection connection = new NpgsqlConnection(datalink.PsconnectionString))
            {
                connection.Open();

                NpgsqlCommand command = connection.CreateCommand();
                NpgsqlTransaction transaction = connection.BeginTransaction(); ;

                command.Connection = connection;
                command.Transaction = transaction;

                try
                {
                    foreach (var item in commandModel)
                    {
                        command.CommandText = item.CommandText;
                        command.Parameters.Clear();
                        command.Parameters.AddRange(item.CommandParameters ?? new NpgsqlParameter[] { });
                        rows += command.ExecuteNonQuery();
                    }
                    message = rows.ToString();
                    transaction.Commit();
                    return true;
                }
                catch (Exception e)
                {
                    message = e.Message;
                    transaction.Rollback();
                    return false;
                }
            }
        }
    }

 

7.PSqlCommandModel

    /// 
    /// CommandModel
    /// 
    public struct PSqlCommandModel
    {
        /// 
        /// CommandText
        /// 
        public string CommandText { set; get; }

        /// 
        /// CommandParameters
        /// 
        public NpgsqlParameter[] CommandParameters { set; get; }
    }
View Code

 

以下是调用,需要Person实体类

    public class Person
    {
        /// 
        /// Constructor
        /// 
        public Person() { }

        /// 
        /// Constructor
        /// 
        /// 
        /// 
        /// 
        /// 
        public Person( string idCard, string realName, bool gender, string address)
        {
            IdCard = idCard;
            RealName = realName;
            Gender = gender;
            Address = address;
        }

        /// 
        /// 
        /// 
        public int PersonId { set; get; }

        /// 
        /// 
        /// 
        public string IdCard { set; get; }

        /// 
        /// 
        /// 
        public string RealName { set; get; }

        /// 
        /// 
        /// 
        public bool Gender { set; get; }

        /// 
        /// 
        /// 
        public string Address { set; get; }

    }
Person Model
        /// 
        /// Insert
        /// 
        /// 
        /// 
        public static int Insert(Person entity)
        {
            string sql = @"insert into ""Person"" (""IdCard"",""RealName"",""Gender"",""Address"") values (@IdCard,@RealName,@Gender,@Address)";
            NpgsqlParameter[] cmdParams = {
                new NpgsqlParameter("@IdCard", NpgsqlDbType.Varchar) { Value = entity.IdCard ?? (object)DBNull.Value },
                new NpgsqlParameter("@RealName", NpgsqlDbType.Varchar) { Value = entity.RealName ?? (object)DBNull.Value },
                new NpgsqlParameter("@Gender", NpgsqlDbType.Bit) { Value = entity.Gender },
                new NpgsqlParameter("@Address", NpgsqlDbType.Varchar) { Value = entity.Address ?? (object)DBNull.Value },
            };
            return PostgresqlBaseDal.ExecuteNonQuery(sql, cmdParams);
        }

        /// 
        /// Update
        /// 
        /// 
        /// 
        public static int Update(Person entity)
        {
            string sql = @"update ""Person"" set ""IdCard""=@IdCard,""RealName""=@RealName,""Gender""=@Gender,""Address""=@Address where ""PersonId""=@PersonId";
            NpgsqlParameter[] cmdParams = {
                new NpgsqlParameter("@PersonId", NpgsqlDbType.Integer) { Value = entity.PersonId },
                new NpgsqlParameter("@IdCard", NpgsqlDbType.Varchar) { Value = entity.IdCard ?? (object)DBNull.Value },
                new NpgsqlParameter("@RealName", NpgsqlDbType.Varchar) { Value = entity.RealName ?? (object)DBNull.Value },
                new NpgsqlParameter("@Gender", NpgsqlDbType.Bit) { Value = entity.Gender },
                new NpgsqlParameter("@Address", NpgsqlDbType.Varchar) { Value = entity.Address ?? (object)DBNull.Value },
            };
            return PostgresqlBaseDal.ExecuteNonQuery(sql, cmdParams);
        }

        /// 
        /// Delete
        /// 
        /// 
        /// 
        public static int Delete(int personId)
        {
            string sql = @"delete from ""Person"" where ""PersonId""=@PersonId";
            NpgsqlParameter[] cmdParams = {
                new NpgsqlParameter("@PersonId", NpgsqlDbType.Integer) { Value = personId },
            };
            return PostgresqlBaseDal.ExecuteNonQuery(sql, cmdParams);
        }

        /// 
        /// Reader
        /// 
        /// 
        /// 
        private static Person Reader(NpgsqlDataReader reader)
        {
            Person newEntity = new Person();
            if (reader != null && !reader.IsClosed)
            {
                if (reader["PersonId"] != DBNull.Value) newEntity.PersonId = (int)reader["PersonId"];
                if (reader["IdCard"] != DBNull.Value) newEntity.IdCard = (string)reader["IdCard"];
                if (reader["RealName"] != DBNull.Value) newEntity.RealName = (string)reader["RealName"];
                if (reader["Gender"] != DBNull.Value) newEntity.Gender = (bool)reader["Gender"];
                if (reader["Address"] != DBNull.Value) newEntity.Address = (string)reader["Address"];
            }
            return newEntity;
        }

        /// 
        /// GetEntity
        /// 
        /// 
        /// 
        public static Person GetEntity(int personId)
        {
            string sql = @"select * from ""Person"" where ""PersonId""=@PersonId";
            NpgsqlParameter[] cmdParams = {
                new NpgsqlParameter("@PersonId", NpgsqlDbType.Integer) { Value = personId },
            };
            return PostgresqlBaseDal.ExecuteReader(Reader, sql, cmdParams);
        }
Person Dal

 

转载于:https://www.cnblogs.com/yuyuefly/p/9662101.html

你可能感兴趣的:(ADO.NET操作PostgreSQL:数据库操作类(已封装))