ADO.NET操作SQL Server:数据库操作类(已封装)
1.增、删、改通用方法
/// <summary>
/// 增、删、改通用方法
/// </summary>
/// <param name="commandText">SqlCommand对象的CommandText属性(sql语句或存储过程名称)</param>
/// <param name="commandParameters">SqlCommand对象的Parameters属性(sql语句或存储过程参数)</param>
/// <param name="commandType">SqlCommand对象的CommandType属性(执行sql语句还是存储过程)</param>
/// <returns></returns>
public static int ExecuteNonQuery(string commandText, SqlParameter[] commandParameters, CommandType commandType = CommandType.Text)
{
using (SqlConnection conn = new SqlConnection(datalink.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(commandText, conn) )
{
cmd.CommandType = commandType;
cmd.Parameters.AddRange(commandParameters ?? new SqlParameter[] { });
conn.Open();
return cmd.ExecuteNonQuery();
}
}
}
2.读取1行记录
/// <summary>
/// 读取1行记录
/// </summary>
/// <typeparam name="T">结果集对应的Model</typeparam>
/// <param name="Reader">读取结果集的SqlDataReader</param>
/// <param name="commandText">SqlCommand对象的CommandText属性(sql语句或存储过程名称)</param>
/// <param name="commandParameters">SqlCommand对象的Parameters属性(sql语句或存储过程参数)</param>
/// <param name="commandType">SqlCommand对象的CommandType属性(执行sql语句还是存储过程)</param>
/// <returns></returns>
public static T ExecuteReader<T>(Func<SqlDataReader, T> Reader, string commandText, SqlParameter[] commandParameters, CommandType commandType = CommandType.Text)
{
T entity = default(T);
using (SqlConnection conn = new SqlConnection(datalink.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
cmd.CommandType = commandType;
cmd.Parameters.AddRange(commandParameters ?? new SqlParameter[] { });
conn.Open();
using (SqlDataReader 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">SqlCommand对象的CommandText属性(sql语句或存储过程名称)</param>
/// <param name="commandParameters">SqlCommand对象的Parameters属性(sql语句或存储过程参数)</param>
/// <param name="commandType">SqlCommand对象的CommandType属性(执行sql语句还是存储过程)</param>
/// <returns></returns>
public static List<T> ExecuteReaderList<T>(Func<SqlDataReader, T> Reader, string commandText, SqlParameter[] commandParameters, CommandType commandType = CommandType.Text)
{
List<T> list = new List<T>();
using (SqlConnection conn = new SqlConnection(datalink.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
cmd.CommandType = commandType;
cmd.Parameters.AddRange(commandParameters ?? new SqlParameter[] { });
conn.Open();
using (SqlDataReader sr = cmd.ExecuteReader())
{
while (sr.Read())
{
list.Add(Reader(sr));
}
}
}
}
return list;
}
4.读取第1行第1列记录
/// <summary>
/// 读取第1行第1列记录
/// </summary>
/// <param name="commandText">SqlCommand对象的CommandText属性(sql语句或存储过程名称)</param>
/// <param name="commandParameters">SqlCommand对象的Parameters属性(sql语句或存储过程参数)</param>
/// <param name="commandType">SqlCommand对象的CommandType属性(执行sql语句还是存储过程)</param>
/// <returns></returns>
public static object ExecuteScalar(string commandText, SqlParameter[] commandParameters, CommandType commandType = CommandType.Text)
{
using (SqlConnection conn = new SqlConnection(datalink.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(commandText, conn))
{
cmd.CommandType = commandType;
cmd.Parameters.AddRange(commandParameters ?? new SqlParameter[] { });
conn.Open();
return cmd.ExecuteScalar();
}
}
}
5.执行事务
/// <summary>
/// 执行事务
/// </summary>
/// <param name="commandModel">Command参数对象列表</param>
/// <param name="message">如果事务提交,返回受影响行数;如果事务回滚,返回异常信息。</param>
/// <returns></returns>
public static bool ExecuteTransaction(List<CommandModel> commandModel, out string message)
{
message = string.Empty;
int rows = ;
using (SqlConnection connection = new SqlConnection(datalink.ConnectionString))
{
connection.Open(); SqlCommand command = connection.CreateCommand();
SqlTransaction 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 SqlParameter[] { });
rows += command.ExecuteNonQuery();
}
message = rows.ToString();
transaction.Commit();
return true;
}
catch (Exception e)
{
message = e.Message;
transaction.Rollback();
return false;
}
}
}
6.批量添加
/// <summary>
/// 批量添加
/// </summary>
/// <param name="destinationTableName">目标数据表表名称</param>
/// <param name="sqlBulkCopyColumnMappings">缓存数据表的列与数据表的列对应关系</param>
/// <param name="dataTable">缓存数据表</param>
public static void BulkInsert(string destinationTableName, List<SqlBulkCopyColumnMapping> sqlBulkCopyColumnMappings, DataTable dataTable)
{
using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(datalink.ConnectionString))
{
sqlBulkCopy.DestinationTableName = destinationTableName;
foreach (var item in sqlBulkCopyColumnMappings)
{
sqlBulkCopy.ColumnMappings.Add(item.SourceColumn, item.DestinationColumn);
}
sqlBulkCopy.WriteToServer(dataTable);
}
}
7.分页查询
/// <summary>
/// 分页查询(SQL Server2012及以上版本支持)
/// </summary>
/// <typeparam name="T">结果集对应的Model</typeparam>
/// <param name="Reader">读取结果集的SqlDataReader</param>
/// <param name="table">数据表名称</param>
/// <param name="limitation">查询条件</param>
/// <param name="sidx">排序字段名称</param>
/// <param name="sord">排序方式</param>
/// <param name="pageIndex">页码</param>
/// <param name="pageSize">每页的数据量</param>
/// <returns></returns>
public static PagedData<T> SearchPagedList<T>(Func<SqlDataReader, T> Reader, string table, string limitation, string sidx, string sord, int pageIndex, int pageSize)
{
PagedData<T> result = new PagedData<T> { PageIndex = pageIndex, PageSize = pageSize }; string sql = string.Empty;
if (string.IsNullOrWhiteSpace(limitation))
{
sql = @"select * from " + table + " order by " + sidx + " " + sord + " offset (@PageIndex -1) * @PageSize rows fetch next @PageSize rows only;select count(*) DataCount from " + table;
}
else
{
sql = @"select * from " + table + " where " + limitation + " order by " + sidx + " " + sord + " offset (@PageIndex -1) * @PageSize rows fetch next @PageSize rows only;select count(*) DataCount from " + table + " where " + limitation;
}
using (SqlConnection conn = new SqlConnection(datalink.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("@PageIndex", SqlDbType.Int).Value = pageIndex;
cmd.Parameters.Add("@PageSize", SqlDbType.Int).Value = pageSize;
conn.Open();
using (SqlDataReader 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["DataCount"];
result.PageCount = result.DataCount % result.PageSize == ? result.DataCount / result.PageSize : result.DataCount / result.PageSize + ;
}
}
}
}
return result;
}
8.辅助类 CommandModel 和 PageData<T>
/// <summary>
/// CommandModel
/// </summary>
public struct CommandModel
{
/// <summary>
/// CommandText
/// </summary>
public string CommandText { set; get; } /// <summary>
/// CommandParameters
/// </summary>
public SqlParameter[] CommandParameters { set; get; }
}
public class PagedData<T>
{
/// <summary>
/// 页索引
/// </summary>
public int PageIndex { set; get; } /// <summary>
/// 每页的数据行数
/// </summary>
public int PageSize { set; get; } /// <summary>
/// 总页码数
/// </summary>
public int PageCount { set; get; } /// <summary>
/// 总行数
/// </summary>
public int DataCount { set; get; } /// <summary>
/// 数据列表
/// </summary>
public List<T> DataList { set; get; }
}
以下是调用,需要Student实体类。
/// <summary>
/// 测试使用Model
/// </summary>
public class Student
{
/// <summary>
/// Constructor
/// </summary>
public Student() { } /// <summary>
/// Constructor
/// </summary>
/// <param name="studentId"></param>
/// <param name="studentNo"></param>
/// <param name="idCard"></param>
/// <param name="realName"></param>
/// <param name="gender"></param>
/// <param name="phone"></param>
/// <param name="birthday"></param>
/// <param name="address"></param>
/// <param name="isValid"></param>
/// <param name="remark"></param>
public Student(Guid studentId, int studentNo, string idCard, string realName, short gender, string phone, DateTime birthday, string address, bool isValid, string remark)
{
StudentId = studentId;
StudentNo = studentNo;
IdCard = idCard;
RealName = realName;
Gender = gender;
Phone = phone;
Birthday = birthday;
Address = address;
IsValid = isValid;
Remark = remark;
} /// <summary>
///
/// </summary>
public Guid StudentId { set; get; } /// <summary>
///
/// </summary>
public int StudentNo { set; get; } /// <summary>
///
/// </summary>
public string IdCard { set; get; } /// <summary>
///
/// </summary>
public string RealName { set; get; } /// <summary>
///
/// </summary>
public short Gender { set; get; } /// <summary>
///
/// </summary>
public string Phone { set; get; } /// <summary>
///
/// </summary>
public DateTime Birthday { set; get; } /// <summary>
///
/// </summary>
public string Address { set; get; } /// <summary>
///
/// </summary>
public bool IsValid { set; get; } /// <summary>
///
/// </summary>
public string Remark { set; get; } }
Student Model
/// <summary>
/// Insert
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public static int Insert(Student entity)
{
string sql = @"insert into [Student] ([StudentId],[StudentNo],[IdCard],[RealName]) values (@StudentId,@StudentNo,@IdCard,@RealName)";
SqlParameter[] cmdParams = {
new SqlParameter("@StudentId", SqlDbType.UniqueIdentifier) { Value = entity.StudentId },
new SqlParameter("@StudentNo", SqlDbType.Int) { Value = entity.StudentNo },
new SqlParameter("@IdCard", SqlDbType.NVarChar) { Value = entity.IdCard ?? (object)DBNull.Value },
new SqlParameter("@RealName", SqlDbType.NVarChar) { Value = entity.RealName ?? (object)DBNull.Value }
};
return SqlBaseDal.ExecuteNonQuery(sql, cmdParams);
} /// <summary>
/// Update
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public static int Update(Student entity)
{
string sql = @"update [Student] set [StudentNo]=@StudentNo,[IdCard]=@IdCard,[RealName]=@RealName where [StudentId]=@StudentId";
SqlParameter[] cmdParams = {
new SqlParameter("@StudentId", SqlDbType.UniqueIdentifier) { Value = entity.StudentId },
new SqlParameter("@StudentNo", SqlDbType.Int) { Value = entity.StudentNo },
new SqlParameter("@IdCard", SqlDbType.NVarChar) { Value = entity.IdCard ?? (object)DBNull.Value },
new SqlParameter("@RealName", SqlDbType.NVarChar) { Value = entity.RealName ?? (object)DBNull.Value }
};
return SqlBaseDal.ExecuteNonQuery(sql, cmdParams);
} /// <summary>
/// Delete
/// </summary>
/// <param name="studentId"></param>
/// <returns></returns>
public static int Delete(Guid studentId)
{
string sql = @"delete from [Student] where [StudentId]=@StudentId";
SqlParameter[] cmdParams = {
new SqlParameter("@StudentId", SqlDbType.UniqueIdentifier) { Value = studentId },
};
return SqlBaseDal.ExecuteNonQuery(sql, cmdParams);
} /// <summary>
/// Reader
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static Student Reader(SqlDataReader reader)
{
Student newEntity = new Student();
if (reader != null && !reader.IsClosed)
{
if (reader["StudentId"] != DBNull.Value) newEntity.StudentId = (Guid)reader["StudentId"];
if (reader["StudentNo"] != DBNull.Value) newEntity.StudentNo = (int)reader["StudentNo"];
if (reader["IdCard"] != DBNull.Value) newEntity.IdCard = (string)reader["IdCard"];
if (reader["RealName"] != DBNull.Value) newEntity.RealName = (string)reader["RealName"];
}
return newEntity;
} /// <summary>
/// GetEntity
/// </summary>
/// <param name="studentId"></param>
/// <returns></returns>
public static Student GetEntity(Guid studentId)
{
string sql = @"select * from [Student] where [StudentId]=@StudentId";
SqlParameter[] cmdParams = {
new SqlParameter("@StudentId", SqlDbType.UniqueIdentifier) { Value = studentId },
};
return SqlBaseDal.ExecuteReader(Reader, sql, cmdParams);
} /// <summary>
/// Insert
/// </summary>
/// <param name="entityList"></param>
/// <param name="message">添加成功后,message存储影响的行数;添加失败后,message存储失败原因。</param>
/// <returns></returns>
public static bool Insert(List<Student> entityList, out string message)
{
List<CommandModel> list = new List<CommandModel>();
foreach (var entity in entityList)
{
CommandModel commandModel = new CommandModel();
commandModel.CommandText = @"insert into [Student] ([StudentId],[StudentNo],[IdCard],[RealName]) values (@StudentId,@StudentNo,@IdCard,@RealName)";
commandModel.CommandParameters = new SqlParameter[]{
new SqlParameter("@StudentId", SqlDbType.UniqueIdentifier) { Value = entity.StudentId },
new SqlParameter("@StudentNo", SqlDbType.Int) { Value = entity.StudentNo },
new SqlParameter("@IdCard", SqlDbType.NVarChar) { Value = entity.IdCard ?? (object)DBNull.Value },
new SqlParameter("@RealName", SqlDbType.NVarChar) { Value = entity.RealName ?? (object)DBNull.Value }
};
list.Add(commandModel);
}
return SqlBaseDal.ExecuteTransaction(list, out message);
} /// <summary>
/// Update
/// </summary>
/// <param name="entityList"></param>
/// <param name="message"></param>
/// <returns></returns>
public static bool Update(List<Student> entityList, out string message)
{
message = string.Empty;
List<CommandModel> list = new List<CommandModel>();
foreach (var entity in entityList)
{
CommandModel commandModel = new CommandModel();
commandModel.CommandText = @"update [Student] set [StudentNo]=@StudentNo,[IdCard]=@IdCard,[RealName]=@RealName where [StudentId]=@StudentId";
commandModel.CommandParameters = new SqlParameter[]{
new SqlParameter("@StudentId", SqlDbType.UniqueIdentifier) { Value = entity.StudentId },
new SqlParameter("@StudentNo", SqlDbType.Int) { Value = entity.StudentNo },
new SqlParameter("@IdCard", SqlDbType.NVarChar) { Value = entity.IdCard ?? (object)DBNull.Value },
new SqlParameter("@RealName", SqlDbType.NVarChar) { Value = entity.RealName ?? (object)DBNull.Value }
};
list.Add(commandModel);
}
return SqlBaseDal.ExecuteTransaction(list, out message);
} /// <summary>
/// Delete
/// </summary>
/// <param name="studentIdList"></param>
/// <param name="message"></param>
/// <returns></returns>
public static bool Delete(List<Guid> studentIdList, out string message)
{
message = string.Empty;
List<CommandModel> list = new List<CommandModel>();
foreach (var item in studentIdList)
{
CommandModel commandModel = new CommandModel();
commandModel.CommandText = @"delete from [Student] where [StudentId]=@StudentId";
commandModel.CommandParameters = new SqlParameter[]{
new SqlParameter("@StudentId", SqlDbType.UniqueIdentifier) { Value = item }
};
list.Add(commandModel);
}
return SqlBaseDal.ExecuteTransaction(list, out message);
}
Student Dal
ADO.NET操作SQL Server:数据库操作类(已封装)的更多相关文章
- [转]C#操作SQL Server数据库
转自:C#操作SQL Server数据库 1.概述 ado.net提供了丰富的数据库操作,这些操作可以分为三个步骤: 第一,使用SqlConnection对象连接数据库: 第二,建立SqlComman ...
- SQL Server学习之路(七):Python3操作SQL Server数据库
0.目录 1.前言 2.准备工作 3.简单测试语句 4.提交与回滚 5.封装成类的写法 1.前言 前面学完了SQL Server的基本语法,接下来学习如何在程序中使用sql,毕竟不能在程序中使用的话, ...
- Python 学习笔记:Python 操作 SQL Server 数据库
最近要将数据写到数据库里,学习了一下如何用 Python 来操作 SQL Server 数据库. 一.连接数据库: 首先,我们要连接 SQL Server 数据库,需要安装 pymssql 这个第三方 ...
- 基于Spring Boot,使用JPA操作Sql Server数据库完成CRUD
完成一个RESTful服务,提供几个访问接口,用来操作较简单的联系人信息,数据保存在Sql Server数据库中. 1.使用STS创建工程. 使用STS创建RESTful工程,可以参考: <用S ...
- 【转】sql server数据库操作大全——常用语句/技巧集锦/经典语句
本文为累计整理,有点乱,凑合着看吧! ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆ ☆ ☆ ☆ sql 宝 典 ☆ ☆ ☆ 2012年-8月 修订版 ☆ ...
- SQL语句操作SQL SERVER数据库登录名、用户及权限
要想成功访问 SQL Server 数据库中的数据, 我们需要两个方面的授权: 获得准许连接 SQL Server 服务器的权利: 获得访问特定数据库中数据的权利(select, update, de ...
- 使用ADO.NET对SQL Server数据库进行訪问
在上一篇博客中我们给大家简介了一下VB.NET语言的一些情况,至于理论知识的学习我们能够利用VB的知识体系为基础.再将面向对象程序设计语言的知识进行融合便可进行编程实战. 假设我们须要訪问一个企业关系 ...
- c# SQL Server数据库操作-数据适配器类:SqlDataAdapter
SqlDataAdapter类主要在MSSQL与DataSet之间执行数据传输工具,本节将介绍如何使用SqlDataAdapter类来填充DataSet和MSSQL执行新增.修改..删除等操作. 功能 ...
- 转发:C#操作SQL Server数据库
转发自:http://www.cnblogs.com/rainman/archive/2012/03/13/2393975.html 1.概述 2.连接字符串的写法 3.SqlConnection对象 ...
- [资料]C#操作SQL Server数据库
1.概述 ado.net提供了丰富的数据库操作,这些操作可以分为三个步骤: 第一,使用SqlConnection对象连接数据库: 第二,建立SqlCommand对象,负责SQL语句的执行和存储过程的调 ...
随机推荐
- lambda架构简介
1.Lambda架构背景介绍 Lambda架构是由Storm的作者Nathan Marz提出的一个实时大数据处理框架.Marz在Twitter工作期间开发了著名的实时大数据处理框架Storm,Lamb ...
- 网络通信和TCP详解
交换机.路由器.服务器组网 1. 通信过程(pc+switch+router+server) 较为复杂的通信过程如:访问 www.baidu.com 注意:一定要配置 PC:IP.NETMASK.DF ...
- python greenlet 背景介绍与实现机制
最近开始研究Python的并行开发技术,包括多线程,多进程,协程等.逐步整理了网上的一些资料,今天整理一下greenlet相关的资料. 并发处理的技术背景 并行化处理目前很受重视, 因为在很多时候,并 ...
- sdc-docker
ssh root@109.105.7.96 sdc-login docker /opt/smartdc/docker ls /var/svc/log/ cat smartdc-application- ...
- protobuf's custom-options
[protobuf's custom-options] protobuf可以设置属性,就像__attribute__可以给函数设置属性一样,protobuf更牛的是可以设置自定义属性.实际就是属性对象 ...
- Prism之初识
首先,简单地介绍说一下单一应用程序与复合应用程序. 一.单一应用程序 看看上面这张图片,假如我们当前的需求是实现主界面如图所示.如果将其构建成具有用户控件的传统 WPF 应用程序,首先应构建一个顶层窗 ...
- 2015年传智播客JavaEE 第168期就业班视频教程14-登录功能需求分析+模块结构命名规范
得先造一个模块,来封装我们的员工模型.登录的就是我们的员工嘛.员工模块属于权限校验系列的,校验叫做auth.进销存模块叫做cn.itcast.erp.invoice.权限模块叫做cn.itcast.e ...
- SOCKET, TCP/UDP, HTTP, FTP 浅析
SOCKET, TCP/UDP, HTTP, FTP (一)TCP/UDP,SOCKET,HTTP,FTP简析 TCP/IP是个协议组,可分为三个层次:网络层.传输层和应用层: 网络层:IP协议. ...
- PHP性能之语言性能优化:安装VLD扩展——检测性能
使用Linux命令安装 //下载安装包 wget http://pecl.php.net/get/vld-0.14.0.tgz //解压包 tar zxvf vld-0.14.0.tgz //进入编译 ...
- c++ template 判断是否为类类型
/* The following code example is taken from the book * "C++ Templates - The Complete Guide" ...