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查询窗口中执 ...
随机推荐
- ASP.NET MVC3快速入门——第四节、添加一个模型
在本节中我们将追加一些类来管理数据库中的电影.这些类将成为我们的MVC应用程序中的“模型”部分.我们将使用一个.NET Framework的被称之为“Entiry Framework”的数据访问技术来 ...
- AT89C 系列单片机解密原理
单片机解密简单就是擦除单片机片内的加密锁定位.由于AT89C系列单片机擦除操作时序设计上的不合理.使在擦除片内程序之前首先擦除加密锁定位成为可能.AT89C系列单片机擦除操作的时序为:擦除开始---- ...
- java获得指定日期的前一天,后一天的代码
/** * 获得指定日期的前一天 * @param specifiedDay * @return * @throws Exception */ public static String getSpec ...
- haporxy 负载elasticsearch
<pre name="code" class="html">-bash-4.1# cat /etc/haproxy/haproxy.cfg glob ...
- linux svn用法
创建一个版本库.项目目录. 创建一个版本库: svnadmin create ~/SVNTestRepo 创建一个项目目录: svn mkdir file:///home/lsf/SVNTestRep ...
- bzoj2243-染色(动态树lct)
解析:增加三个变量lc(最左边的颜色),rc(最右边的颜色),sum(连续相同颜色区间段数).然后就是区间合并的搞法.我就不详细解释了,估计你已经想到 如何做了. 代码 #include<cst ...
- Java学习作业(14.4.21)
前三次作业都是基础语法.真的好水啊.从这次开始记录. 1.编写Java程序,把当前目录下扩展名为txt的文件的扩展名全部更名为back. import java.io.*; import java.l ...
- 把一个select查询结果插入到一个表(可选指定字段和值实例)
把一个select查询结果插入到一个表(可选指定字段和值实例) insert into bak (cc,yf) select cc,9 from ket insert into bak (cc,yf ...
- 为github帐号添加SSH keys
为github帐号添加SSH keys 2012-05-26 00:05 34279人阅读 评论(6) 收藏 举报 ssh文本编辑gitvim工具up 使用git clone命令从github上同步g ...
- nodejs报错 events.js:72 throw er; // Unhandled 'error' event
var http = require('http'); var handlerRequest = function(req,res){ res.end('hello');}; var webServe ...