ADO.NET操作PostgreSQL:数据库操作类(已封装)
1.增、删、改通用方法
/// <summary>
/// 增、删、改通用方法
/// </summary>
/// <param name="commandText">Command对象的CommandText属性(sql语句或存储过程名称)</param>
/// <param name="commandParameters">Command对象的Parameters属性(sql语句或存储过程参数)</param>
/// <returns></returns>
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行记录
/// <summary>
/// 读取1行记录
/// </summary>
/// <typeparam name="T">结果集对应的Model</typeparam>
/// <param name="Reader">读取结果集的SqlDataReader</param>
/// <param name="commandText">Command对象的CommandText属性(sql语句或存储过程名称)</param>
/// <param name="commandParameters">Command对象的Parameters属性(sql语句或存储过程参数)</param>
/// <returns></returns>
public static T ExecuteReader<T>(Func<NpgsqlDataReader, T> 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行记录
/// <summary>
/// 读取n行记录
/// </summary>
/// <typeparam name="T">结果集对应的Model</typeparam>
/// <param name="Reader">读取结果集的SqlDataReader</param>
/// <param name="commandText">Command对象的CommandText属性(sql语句或存储过程名称)</param>
/// <param name="commandParameters">Command对象的Parameters属性(sql语句或存储过程参数)</param>
/// <returns></returns>
public static List<T> ExecuteReaderList<T>(Func<NpgsqlDataReader, T> Reader, string commandText, NpgsqlParameter[] commandParameters)
{
List<T> list = new List<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())
{
list.Add(Reader(sr));
}
}
}
}
return list;
}
4.读取第1行第1列记录
/// <summary>
/// 读取第1行第1列记录
/// </summary>
/// <param name="commandText">Command对象的CommandText属性(sql语句或存储过程名称)</param>
/// <param name="commandParameters">Command对象的Parameters属性(sql语句或存储过程参数)</param>
/// <returns></returns>
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.分页查询
/// <summary>
/// 分页查询
/// </summary>
/// <typeparam name="T">结果集对应的Model</typeparam>
/// <param name="Reader">读取结果集的DataReader</param>
/// <param name="table">数据表名称</param>
/// <param name="limitation">查询条件</param>
/// <param name="sidx">排序字段名称</param>
/// <param name="sord">排序方式</param>
/// <param name="page">页码</param>
/// <param name="rows">每页的数据量</param>
/// <returns></returns>
public static PagedData<T> SearchPagedList<T>(Func<NpgsqlDataReader, T> Reader, string table, string sidx, string sord, int page, int rows, string limitation)
{
PagedData<T> result = new PagedData<T> { 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<T>();
while (sr.Read())
{
result.DataList.Add(Reader(sr));
}
bool bln = sr.NextResult();
while (sr.Read())
{
result.DataCount = (int)sr[];
result.PageCount = result.DataCount % result.PageSize == ? result.DataCount / result.PageSize : result.DataCount / result.PageSize + ;
}
}
}
}
return result;
}
6.执行事务
/// <summary>
/// 执行事务
/// </summary>
/// <param name="commandModel">Command参数对象列表</param>
/// <param name="message">如果事务提交,返回受影响行数;如果事务回滚,返回异常信息。</param>
/// <returns></returns>
public static bool ExecuteTransaction(List<PSqlCommandModel> commandModel, out string message)
{
message = string.Empty;
int rows = ;
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
/// <summary>
/// CommandModel
/// </summary>
public struct PSqlCommandModel
{
/// <summary>
/// CommandText
/// </summary>
public string CommandText { set; get; } /// <summary>
/// CommandParameters
/// </summary>
public NpgsqlParameter[] CommandParameters { set; get; }
}
以下是调用,需要Person实体类
public class Person
{
/// <summary>
/// Constructor
/// </summary>
public Person() { } /// <summary>
/// Constructor
/// </summary>
/// <param name="idCard"></param>
/// <param name="realName"></param>
/// <param name="gender"></param>
/// <param name="address"></param>
public Person( string idCard, string realName, bool gender, string address)
{
IdCard = idCard;
RealName = realName;
Gender = gender;
Address = address;
} /// <summary>
///
/// </summary>
public int PersonId { set; get; } /// <summary>
///
/// </summary>
public string IdCard { set; get; } /// <summary>
///
/// </summary>
public string RealName { set; get; } /// <summary>
///
/// </summary>
public bool Gender { set; get; } /// <summary>
///
/// </summary>
public string Address { set; get; } }
Person Model
/// <summary>
/// Insert
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
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);
} /// <summary>
/// Update
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
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);
} /// <summary>
/// Delete
/// </summary>
/// <param name="personId"></param>
/// <returns></returns>
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);
} /// <summary>
/// Reader
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
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;
} /// <summary>
/// GetEntity
/// </summary>
/// <param name="personId"></param>
/// <returns></returns>
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
ADO.NET操作PostgreSQL:数据库操作类(已封装)的更多相关文章
- ado.net的简单数据库操作(一)
摘要:接下来的几篇博客将要讲到如何使用ado.net实现简单的数据库操作,包括增删改等内容.首先会介绍基础的数据库操作,然后以一个实例来进行讲解,这个实例会把一个数据表读取到winform上,然后在w ...
- 关于PHP建立数据库访问类的封装以及操作php单例模式连接数据库封装类
建立数据库访问类的封装 <?php class DBDA { public $host = "localhost"; //服务器地址 public $ui ...
- Redis操作,数据库操作
Redis操作,数据库操作 案例1:源码安装Redis缓存服务 案例2:常用Redis数据库操作指令 案例3:配置Redis主从服务器 1 案例1:源码安装Redis缓存服务 1.1 问题 本案例要求 ...
- ado.net的简单数据库操作(二)之封装SqlHelperl类
今天我书接上回,接着昨天的ado.net的数据库操作的相关知识来讲哈! 从上篇文章给出的实例来看,你一定会发现,操作数据库其实还挺麻烦的,就连一个最简单的数据库操作语句都要包括 定义数据库连接字符串. ...
- Python 操作 PostgreSQL 数据库
我使用的是 Python 3.7.0 PostgreSQL可以使用psycopg2模块与Python集成. sycopg2是用于Python编程语言的PostgreSQL数据库适配器. psycopg ...
- ado.net的简单数据库操作(三)——简单增删改查的实际应用
果然,在犯困的时候就该写写博客,写博客就不困了,哈哈! 上篇我记录了自己的SqlHelper的开发过程,今天记录一下如何使用这个sqlhelper书写一个具有简单增删改查的小实例啦. 实例描述:在数据 ...
- hibernate 操作 Postgresql 数据库报 operator does not exist: integer = character varying
网上的说法如下: Java开发Postgresql 数据库兼容应用的问题,与Oracle有一些不同: Java类型映射数据库类型的不同,Oracle jdbc驱动程序处理Java String类型可正 ...
- C#/Python/MATLAB操作PostgreSQL数据库
PostgreSQL数据库是一个功能非常强大的开源数据库,支持多种SQL特性,非常好用.此外由于结合PostGIS可以实现空间数据库功能,故非常适合GIS领域的使用.本文旨在介绍C#.Python.M ...
- 使用JdbcTemplate简化JDBC操作 实现数据库操作
使用Spring JDBC框架方遍简单的完成JDBC操作,满足性能的需求且灵活性高. Spring JDBC框架由4个部分组成,即core.datasource.object.support. org ...
- 操作redis数据库 & 操作Excel & 开发接口
操作redis数据库: string类型 1. 增 set,传俩个参数 key value(只要是字符串就行)2. 删 delete 传一个参数 key3. 修改 set 在目标key重新传参 key ...
随机推荐
- 西南交通大学结构服役安全及力学基础创新团队在Wiley出版英文专著(转载)
近日,西南交通大学力学与工程学院康国政教授与阚前华副教授受邀由John Wiley & Sons Ltd公司出版了英文专著 “Cyclic plasticity of Engineering ...
- httplib:AttributeError: 'module' object has no attribute 'HTTPConnection'
# -*-coding:gb2312-*- #Function:学习python的httplib模块 import httplib conn = httplib.HTTPConnection(&quo ...
- iis 应用程序连接池 在计算机“.”上没有找到WAS服务
重新打开控制面板----打开或关闭windows功能,全部勾选internet information services 可承载的web核心. internet信息服务.microsoft.net f ...
- 10-能不能组成m
/* 找数达人 时间限制:1000 ms | 内存限制:65535 KB 难度:2 描述 小明最近做出了一道题:如何在一组数 ...
- JsonConvert.SerializeObject 空值处理
var settings = new JsonSerializerSettings() { ContractResolver= new NullToEmptyStringResolver() }; v ...
- MVC仓储使用join
代码: var result = from mpc in this.Context.Set<Domain.S_MENU_PURVIEWCODE>() join menu in this.C ...
- "UX"将会是下一个Buzzword?
“用户体验非常重要”.“没有用户体验就没有产品”.“UX就是一切”.不知道从何时开始,用户体验(UX) 这个名词已经变得如此多见了,但是人们真正的认识.认清了什么是用户体验了吗?设计师们常挂在嘴边的用 ...
- 将C语言宏定义数值转换成字符串!
将C语言宏定义转换成字符串! 摘自:https://blog.csdn.net/happen23/article/details/50602667 2016年01月28日 19:15:47 六个九十度 ...
- failed creating java jvm.dll
启动tomcat服务时出现错误failed creating java jvm.dll的解决办法 把jdk\bin目录下的msvcr71.dll 或msvcr100.dll 复制到tomcat安装目录 ...
- 专2-第一课 Ubuntu系统安装与配置
1.1 使用VMware安装Ubuntu 1.1.1 准备工作 1)VMware的安装包 VMware至少要用10.0版本,本文采用最新的VMware12版本,这个版本对USB3.0的支持更加完善稳定 ...