C# sql Helper
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Threading;
namespace Common
{
public enum AutoRollback
{
/// <summary>
/// 手动回滚
/// </summary>
None, /// <summary>
/// 除查询语句以外回滚
/// </summary>
ExceptQuery, /// <summary>
/// 任何情况下回滚
/// </summary>
Always,
} public class SqlDbContext : IDisposable
{
public AutoRollback AutoRollback { get; private set; }
private string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
public string ConnectionString { get { return connectionString; } } public SqlConnection Connection { get; private set; }
public SqlTransaction Transaction { get; private set; } public SqlDbContext(AutoRollback auto = AutoRollback.ExceptQuery) :
this(ConfigurationManager.ConnectionStrings["conn"].ConnectionString, auto)
{
} public SqlDbContext(string connectionString, AutoRollback auto)
{
this.Connection = new SqlConnection(connectionString);
this.AutoRollback = auto;
} public void Dispose()
{
this.EndTrans();
this.Close(); if (this.Connection != null)
this.Connection.Dispose(); this.Connection = null;
this.Transaction = null;
} #region Transaction
/// <summary>
/// 开启事务
/// </summary>
public void BeginTrans()
{
if (this.Transaction != null)
this.Transaction.Dispose();
this.Open();
this.Transaction = this.Connection.BeginTransaction();
} /// <summary>
/// 提交事务
/// </summary>
public void CommitTrans()
{
if (this.Transaction != null)
this.Transaction.Commit();
} /// <summary>
/// 回滚
/// </summary>
public void RollbackTrans()
{
if (this.Transaction != null)
this.Transaction.Rollback();
} /// <summary>
/// 结束事务,释放资源
/// </summary>
public void EndTrans()
{
if (this.Transaction != null)
this.Transaction.Dispose();
this.Transaction = null;
}
#endregion #region Exec Command #region 执行sql脚本块
/// <summary>
/// 执行Sql脚本块
/// </summary>
/// <param name="dbType">0为access,1为sqlserver</param>
/// <param name="connectionString">数据库连接</param>
/// <param name="pathToScriptFile">脚本路径,物理路径</param>
/// <returns></returns>
public bool Go(string strSql, CommandType commandType = CommandType.Text)
{ this.Open(); try
{
using (SqlCommand cmd = new SqlCommand()
{
CommandText = strSql,
CommandType = commandType,
Connection = this.Connection,
})
{
if (this.Transaction != null)
cmd.Transaction = this.Transaction; foreach (string Sql in SqlList(strSql))
{
cmd.CommandText = Sql;
cmd.ExecuteNonQuery();
}
}
return true;
}
catch
{
if (this.AutoRollback != AutoRollback.None)
this.RollbackTrans();
throw;
}
}
private static string[] SqlList(string StrSql)
{
string[] _strList = StrSql.Split(new string[] { "GO" }, StringSplitOptions.RemoveEmptyEntries);
return _strList;
}
#endregion
/// <summary>
/// 执行SQL语句, 此方法用于插入、更新操作
/// 返回受影响的行数
/// </summary>
/// <param name="text">SQL执行语句</param>
/// <param name="commandType">语句类型</param>
/// <param name="args">语句参数</param>
/// <returns>返回受影响的行数</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
public int Execute(
string text,
CommandType commandType = CommandType.Text,
params SqlParameter[] args)
{
this.Open(); try
{
using (SqlCommand cmd = new SqlCommand()
{
CommandText = text,
CommandType = commandType,
Connection = this.Connection,
})
{
if (this.Transaction != null)
cmd.Transaction = this.Transaction; AddParameterToCommand(cmd, args);
return cmd.ExecuteNonQuery();
} }
catch
{
if (this.AutoRollback != AutoRollback.None)
this.RollbackTrans();
throw;
}
} /// <summary>
/// SqlBulkCopy 大批量数据插入
/// </summary>
/// <param name="table">内存表 Datatable</param>
/// <param name="destinationTableName">服务器上表的名称</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
public void ExecuteBulkCopy(DataTable table,
string destinationTableName
)
{
this.BeginTrans();
try
{
using (SqlBulkCopy copy = new SqlBulkCopy(Connection, SqlBulkCopyOptions.Default, this.Transaction))
{
copy.DestinationTableName = destinationTableName;
for (int i = ; i < table.Columns.Count; i++)
{
copy.ColumnMappings.Add(table.Columns[i].ColumnName, table.Columns[i].ColumnName);
}
copy.WriteToServer(table);
this.CommitTrans();
}
}
catch
{
if (this.AutoRollback != AutoRollback.None)
this.RollbackTrans();
throw;
}
} /// <summary>
/// 执行SQL语句,并返回查询结果的第一行第一列的值要返回什么样的值,就T 里面写入什么类型
/// </summary>
/// <typeparam name="T">返回结果类型</typeparam>
/// <param name="query">SQL语句</param>
/// <param name="commandType">语句类型</param>
/// <param name="args">语句参数</param>
/// <returns>返回查询结果的第一行第一列的值</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
public T ExecuteScalar<T>(
string query,
CommandType commandType = CommandType.Text,
params SqlParameter[] args)
{
this.Open(); try
{
using (SqlCommand cmd = new SqlCommand()
{
CommandText = query,
CommandType = commandType,
Connection = this.Connection,
})
{
if (this.Transaction != null)
cmd.Transaction = this.Transaction; AddParameterToCommand(cmd, args);
object obj = cmd.ExecuteScalar();
if (obj == null || obj == DBNull.Value)
return default(T);
return (T)obj;
}
}
catch
{
if (this.AutoRollback != AutoRollback.None)
this.RollbackTrans();
throw;
}
} /// <summary>
/// 执行SQL语句,并返回查询结果的第一行第一列的值
/// </summary>
/// <typeparam name="T">返回结果类型</typeparam>
/// <param name="query">SQL语句</param>
/// <param name="commandType">语句类型</param>
/// <param name="args">语句参数</param>
/// <returns>返回查询结果的第一行第一列的值</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
public int ExecuteScalar(
string query,
CommandType commandType = CommandType.Text,
params SqlParameter[] args)
{
this.Open(); try
{
using (SqlCommand cmd = new SqlCommand()
{
CommandText = query,
CommandType = commandType,
Connection = this.Connection,
})
{
if (this.Transaction != null)
cmd.Transaction = this.Transaction; AddParameterToCommand(cmd, args);
object obj = cmd.ExecuteScalar();
return Convert.ToInt32(obj);
}
}
catch
{
if (this.AutoRollback != AutoRollback.None)
this.RollbackTrans();
throw;
}
} /// <summary>
/// 执行SQL语句,并返回查询结果的实体类集合
/// 实体类的属性需包含查询结果的表头
/// </summary>
/// <typeparam name="T">查询结果的实体类</typeparam>
/// <param name="query">SQL语句</param>
/// <param name="commandType">语句类型</param>
/// <param name="args">语句参数</param>
/// <returns>返回结果的实体类集合</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
public List<T> Query<T>(
string query,
CommandType commandType = CommandType.Text,
params SqlParameter[] args)
where T : new()
{
this.Open(); try
{
using (SqlCommand cmd = new SqlCommand()
{
CommandText = query,
CommandType = commandType,
Connection = this.Connection,
})
{
if (this.Transaction != null)
cmd.Transaction = this.Transaction; AddParameterToCommand(cmd, args);
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<T> result = new List<T>();
var columns = GetColumns<T>(reader);
while (reader.Read())
{
T obj = CreateObject<T>(reader, columns);
result.Add(obj);
}
return result;
}
}
}
catch
{
if (AutoRollback == AutoRollback.Always)
this.RollbackTrans();
throw;
}
} /// <summary>
/// 执行SQL语句,返回 SqlDataReader
/// </summary>
/// <param name="query">SQL语句</param>
/// <param name="commandType">语句类型</param>
/// <param name="args">语句参数</param>
/// <returns>SqlDataReader</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
public SqlDataReader GetDataReader(
string query,
CommandType commandType = CommandType.Text,
params SqlParameter[] args)
{
this.Open(); try
{
using (SqlCommand cmd = new SqlCommand()
{
CommandText = query,
CommandType = commandType,
Connection = this.Connection,
})
{
if (this.Transaction != null)
cmd.Transaction = this.Transaction; AddParameterToCommand(cmd, args);
return cmd.ExecuteReader();
}
}
catch
{
if (AutoRollback == AutoRollback.Always)
this.RollbackTrans();
throw;
}
} /// <summary>
/// 执行SQL语句,以DataTable对象作为结果返回查询结果
/// </summary>
/// <param name="query">SQL语句</param>
/// <param name="commandType">语句类型</param>
/// <param name="args">语句参数</param>
/// <returns>DataTable对象</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
public DataTable QueryDT(
string query,
CommandType commandType = CommandType.Text,
params SqlParameter[] args)
{
this.Open();
try
{
using (SqlCommand cmd = new SqlCommand()
{
CommandText = query,
CommandType = commandType,
Connection = this.Connection,
})
{
if (this.Transaction != null)
cmd.Transaction = this.Transaction; AddParameterToCommand(cmd, args);
DataTable result = new DataTable();
using (SqlDataAdapter ad = new SqlDataAdapter())
{
ad.SelectCommand = cmd;
ad.Fill(result);
return result;
}
}
}
catch
{
if (AutoRollback == AutoRollback.Always)
this.RollbackTrans();
throw;
}
} /// <summary>
/// 执行SQL语句,并返回查询结果的第一个对象, 如果没有查询结果则为NULL
/// 实体类的属性需包含查询结果的表头
/// </summary>
/// <typeparam name="T">查询结果的实体类</typeparam>
/// <param name="query">SQL语句</param>
/// <param name="commandType">语句类型</param>
/// <param name="args">语句参数</param>
/// <returns>查询结果的第一个对象,如果没有查询结果则为NULL</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
public T FirstOrDefault<T>(
string query,
CommandType commandType = CommandType.Text,
params SqlParameter[] args)
where T : new()
{
this.Open(); try
{
using (SqlCommand cmd = new SqlCommand()
{
CommandText = query,
CommandType = commandType,
Connection = this.Connection,
})
{
if (this.Transaction != null)
cmd.Transaction = this.Transaction; AddParameterToCommand(cmd, args); using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
var columns = GetColumns<T>(reader);
reader.Read();
return CreateObject<T>(reader, columns);
} return default(T);
}
}
}
catch
{
if (AutoRollback == AutoRollback.Always)
this.RollbackTrans();
throw;
}
}
#endregion #region HelperMethods
public void Open()
{
if (this.Connection != null &&
this.Connection.State != ConnectionState.Open)
this.Connection.Open();
} public void Close()
{
if (this.Connection != null)
this.Connection.Close();
} public SqlCommand CreateCommand()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = this.Connection;
if (this.Transaction != null)
cmd.Transaction = this.Transaction; return cmd;
} public static void AddParameterToCommand(SqlCommand cmd, SqlParameter[] args)
{
if (args != null && args.Length > )
{
foreach (var arg in args)
{
if (arg != null)
{
if (arg.IsNullable && arg.Value == null)
{
arg.Value = DBNull.Value;
} cmd.Parameters.Add(arg);
}
}
}
} private static PropertyInfo[] GetColumns<T>(SqlDataReader reader)
{
List<T> result = new List<T>();
Type type = typeof(T);
var columns = new List<PropertyInfo>(reader.FieldCount);
var props = type.GetProperties();
string name; for (int i = ; i < reader.FieldCount; i++)
{
name = reader.GetName(i);
for (int j = ; j < props.Length; j++)
{
if (props[j].Name.ToLower() == name.ToLower())
{
columns.Add(props[j]);
break;
}
}
} return columns.ToArray();
} private static T CreateObject<T>(SqlDataReader reader, PropertyInfo[] columns) where T : new()
{
T result = Activator.CreateInstance<T>();
for (int i = ; i < columns.Length; i++)
{
columns[i].SetValue(result, reader[columns[i].Name] == DBNull.Value ? null : reader[columns[i].Name], null);
} return result;
}
#endregion }
}
C# sql Helper的更多相关文章
- 微软原版SQL Helper
代码 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-- ...
- Java sql helper[转]
原文:http://www.cnblogs.com/beijiguangyong/archive/2011/12/10/2302737.html package sql; import java.sq ...
- sql helper
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.C ...
- [Android 开发教程(1)]-- Saving Data in SQL Databases
Saving data to a database is ideal for repeating or structured data, such as contact information. Th ...
- Android学习笔记——保存数据到SQL数据库中(Saving Data in SQL Databases)
知识点: 1.使用SQL Helper创建数据库 2.数据的增删查改(PRDU:Put.Read.Delete.Update) 背景知识: 上篇文章学习了保存文件,今天学习的是保存数据到SQL数据库中 ...
- 数据库Error:The ScriptCollection in ScriptName not find
System.InvalidOperationException: The ScriptCollection in ScriptName not find 在 WMI.SQL.HELPER.CONFI ...
- java攻城狮之路(Android篇)--ListView与ContentProvider
一.ListView 1.三种Adapter构建ListView ListView添加条目的时候, 可以使用setAdapter(ListAdapter)方法, 常用的ListAdapter有三种 B ...
- java攻城狮之路(Android篇)--SQLite
一.Junit 1.怎么使用 在AndroidManifest.xml文件中进行配置, 在manifest借点下配置instrumentation, 在application借点下 ...
- Oracle 数据库中不同事务并发访问的问题
现象 以SQL/Helper为例,打开不同的SQL窗口,对同一个表格进行操作,如下所示. 窗口1:当执行更新任务.紧接着执行查询时获得一组查询结果.结果是对的. 窗口2:而在另外一个SQL查询窗口中执 ...
随机推荐
- IC封装图片认识(一):BGA
在上篇文章<常用IC封装技术介绍>第一个提到的IC封装形式就是BGA,全称是Ball Grid Array(球栅阵列结构的PCB),它是集成电路采用有机载板的一种封装法.其具有以下五个特点 ...
- Windows 8.1 正式版 MSDN第二版 官方简体中文/英文版 (专业版/企业版)
说明:文件名cn开头的是简中版文件名en开头的是英文版文件名含x64的为64位版本文件名含x86的为32位版本文件名含enterprise的为企业版文件名含pro_vl的为专业批量授权版文件名不含en ...
- Ubuntu 14.04远程登录服务器--openssh的安装和配置简明步骤
如果要主机通过网络操作嵌入式板子,ttelnet就够了,但是 如果要相互传文件,则必须使用另外一个强大的软件SSH.更完整的步骤和截图请参考http://jingyan.baidu.com/artic ...
- 03_Elasticsearch如何安装以及相关插件的介绍
03_Elasticsearch如何安装以及相关插件的介绍 elasticsearch -d (-d参数是为了让服务后台运行) Elasticsearch 目录结构: 文件夹 作用 /bin 运行El ...
- JavaScript面向对象之类的继承
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 初学github
在公司一直用的SVN做版本管理,倒也没什么问题.最近想自己在家写点东西,上班的时候又想偷偷地写.代码经常在两个地方同步,很是辛苦.反正写的只是一些用来学习测试的代码,干脆放到github上. 1.登录 ...
- Spark函数详解系列之RDD基本转换
摘要: RDD:弹性分布式数据集,是一种特殊集合 ‚ 支持多种来源 ‚ 有容错机制 ‚ 可以被缓存 ‚ 支持并行操作,一个RDD代表一个分区里的数据集 RDD有两种操作算子: ...
- SICP 习题 (1.9) 解题总结
SICP 习题 1.9 开始针对“迭代计算过程”和“递归计算过程”,有关迭代计算过程和递归计算过程的内容在书中的1.2.1节有详细讨论,要完成习题1.9,必须完全吃透1.2.1节的内容,不然的话,即使 ...
- SEO 外链 内链 的定义
外链 外链就是指从别的网站导入到自己网站的链接.导入链接对于网站优化来说是非常重要的一个过程.导入链接的质量(即导入链接所在页面的权重)直接决定了我们的网站在搜索引擎中的权重. 外链是互联网的血液,是 ...
- [Spring入门学习笔记][Spring Boot]
什么是Spring Boot Spring Boot正是在这样的一个背景下被抽象出来的开发框架,它本身并不提供Spring框架的核心特性以及扩展功能,只是用于快速.敏捷地开发新一代基于Spring框架 ...