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:数据库操作类(已封装)的更多相关文章

  1. [转]C#操作SQL Server数据库

    转自:C#操作SQL Server数据库 1.概述 ado.net提供了丰富的数据库操作,这些操作可以分为三个步骤: 第一,使用SqlConnection对象连接数据库: 第二,建立SqlComman ...

  2. SQL Server学习之路(七):Python3操作SQL Server数据库

    0.目录 1.前言 2.准备工作 3.简单测试语句 4.提交与回滚 5.封装成类的写法 1.前言 前面学完了SQL Server的基本语法,接下来学习如何在程序中使用sql,毕竟不能在程序中使用的话, ...

  3. Python 学习笔记:Python 操作 SQL Server 数据库

    最近要将数据写到数据库里,学习了一下如何用 Python 来操作 SQL Server 数据库. 一.连接数据库: 首先,我们要连接 SQL Server 数据库,需要安装 pymssql 这个第三方 ...

  4. 基于Spring Boot,使用JPA操作Sql Server数据库完成CRUD

    完成一个RESTful服务,提供几个访问接口,用来操作较简单的联系人信息,数据保存在Sql Server数据库中. 1.使用STS创建工程. 使用STS创建RESTful工程,可以参考: <用S ...

  5. 【转】sql server数据库操作大全——常用语句/技巧集锦/经典语句

    本文为累计整理,有点乱,凑合着看吧! ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆ ☆ ☆ ☆ sql 宝 典 ☆ ☆ ☆ 2012年-8月 修订版 ☆ ...

  6. SQL语句操作SQL SERVER数据库登录名、用户及权限

    要想成功访问 SQL Server 数据库中的数据, 我们需要两个方面的授权: 获得准许连接 SQL Server 服务器的权利: 获得访问特定数据库中数据的权利(select, update, de ...

  7. 使用ADO.NET对SQL Server数据库进行訪问

    在上一篇博客中我们给大家简介了一下VB.NET语言的一些情况,至于理论知识的学习我们能够利用VB的知识体系为基础.再将面向对象程序设计语言的知识进行融合便可进行编程实战. 假设我们须要訪问一个企业关系 ...

  8. c# SQL Server数据库操作-数据适配器类:SqlDataAdapter

    SqlDataAdapter类主要在MSSQL与DataSet之间执行数据传输工具,本节将介绍如何使用SqlDataAdapter类来填充DataSet和MSSQL执行新增.修改..删除等操作. 功能 ...

  9. 转发:C#操作SQL Server数据库

    转发自:http://www.cnblogs.com/rainman/archive/2012/03/13/2393975.html 1.概述 2.连接字符串的写法 3.SqlConnection对象 ...

  10. [资料]C#操作SQL Server数据库

    1.概述 ado.net提供了丰富的数据库操作,这些操作可以分为三个步骤: 第一,使用SqlConnection对象连接数据库: 第二,建立SqlCommand对象,负责SQL语句的执行和存储过程的调 ...

随机推荐

  1. pythonNET day05

    孤儿进程 父进程先于子进程退出,此时子进程就会成为孤儿进程. 孤儿进程会被系统指定的进程收养,即系统进程会成为该孤儿进程新的父进程.孤儿进程退出时该父进程会处理退出状态 僵尸进程 子进程先于父进程退出 ...

  2. Protocol入门

    参考:http://haoxiang.org/2011/08/ios-delegate-and-protocol/ 介绍: Protocol在iOS中就是协议,简单的理解就是一组函数的集合,这个集合中 ...

  3. 31_java之项目中的数据库操作

    01项目训练目标 * A: 项目训练目标 * a: 项目目标 * 综合运用前面所学习的知识点 * 熟练View层.Service层.Dao层之间的方法相互调用操作. * 熟练dbutils操作数据库表 ...

  4. 学习 TCP 三次握手和四次挥手

    TCP三次握手和四次挥手的问题在面试中是最为常见的考点之一.很多读者都知道三次和四次,但是如果问深入一点,他们往往都无法作出准确回答. 本篇尝试使用动画来对这个知识点进行讲解,期望读者们可以更加简单地 ...

  5. 温(Xue)习排序算法

    最近忙着找工作,虽然排序算法用得到的情况不多,但不熟悉的话心里始终还是感觉没底. 于是今天给温习了其中的四个排序算法(与其说是温习,不如说是学习...因为感觉自己好像从来木有掌握过它们...) 一.选 ...

  6. leetcode 235 236 二叉树两个节点的最近公共祖先

    描述: 给定二叉树两个节点,求其最近公共祖先.最近即所有公共祖先中深度最深的. ps:自身也算自身的祖先. 235题解决: 这是二叉搜索树,有序的,左边小右边大. TreeNode* lowestCo ...

  7. hibernate与ssm多数据源配置

    hibernate: 1.配置多个数据源,比如2个:hibernate.cfg1.xml~hibernate.cfg8.xml <?xml version='1.0' encoding='UTF ...

  8. SqlMapConfig.xml配置文件中的mapper映射器标签

    Mapper配置的几种方式: 1. <mapper resource=" "/> 使用相对于类路径的资源 如:<mapper resource="com ...

  9. AlexNet 2012

    AlexNet             Alexnet是一年一度的ImageNet大型视觉识别挑战赛(ILSVRC)2012年冠军,ILSVRC使用ImageNet的一个子集,分为1000种类别,每种 ...

  10. 20172325《Java程序设计》第一周学习总结

    20172325<Java程序设计>第一周学习总结 教材学习内容总结 第一章 1.1软件质量 软件工程是一门关于高质量软件开发的技术和理论的学科. 高质量软件的特征 1.2 数据结构 软件 ...