1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Configuration;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Reflection;
  8. using System.Threading;
  9. namespace Common
  10. {
  11. public enum AutoRollback
  12. {
  13. /// <summary>
  14. /// 手动回滚
  15. /// </summary>
  16. None,
  17.  
  18. /// <summary>
  19. /// 除查询语句以外回滚
  20. /// </summary>
  21. ExceptQuery,
  22.  
  23. /// <summary>
  24. /// 任何情况下回滚
  25. /// </summary>
  26. Always,
  27. }
  28.  
  29. public class SqlDbContext : IDisposable
  30. {
  31. public AutoRollback AutoRollback { get; private set; }
  32. private string connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
  33. public string ConnectionString { get { return connectionString; } }
  34.  
  35. public SqlConnection Connection { get; private set; }
  36. public SqlTransaction Transaction { get; private set; }
  37.  
  38. public SqlDbContext(AutoRollback auto = AutoRollback.ExceptQuery) :
  39. this(ConfigurationManager.ConnectionStrings["conn"].ConnectionString, auto)
  40. {
  41. }
  42.  
  43. public SqlDbContext(string connectionString, AutoRollback auto)
  44. {
  45. this.Connection = new SqlConnection(connectionString);
  46. this.AutoRollback = auto;
  47. }
  48.  
  49. public void Dispose()
  50. {
  51. this.EndTrans();
  52. this.Close();
  53.  
  54. if (this.Connection != null)
  55. this.Connection.Dispose();
  56.  
  57. this.Connection = null;
  58. this.Transaction = null;
  59. }
  60.  
  61. #region Transaction
  62. /// <summary>
  63. /// 开启事务
  64. /// </summary>
  65. public void BeginTrans()
  66. {
  67. if (this.Transaction != null)
  68. this.Transaction.Dispose();
  69. this.Open();
  70. this.Transaction = this.Connection.BeginTransaction();
  71. }
  72.  
  73. /// <summary>
  74. /// 提交事务
  75. /// </summary>
  76. public void CommitTrans()
  77. {
  78. if (this.Transaction != null)
  79. this.Transaction.Commit();
  80. }
  81.  
  82. /// <summary>
  83. /// 回滚
  84. /// </summary>
  85. public void RollbackTrans()
  86. {
  87. if (this.Transaction != null)
  88. this.Transaction.Rollback();
  89. }
  90.  
  91. /// <summary>
  92. /// 结束事务,释放资源
  93. /// </summary>
  94. public void EndTrans()
  95. {
  96. if (this.Transaction != null)
  97. this.Transaction.Dispose();
  98. this.Transaction = null;
  99. }
  100. #endregion
  101.  
  102. #region Exec Command
  103.  
  104. #region 执行sql脚本块
  105. /// <summary>
  106. /// 执行Sql脚本块
  107. /// </summary>
  108. /// <param name="dbType">0为access,1为sqlserver</param>
  109. /// <param name="connectionString">数据库连接</param>
  110. /// <param name="pathToScriptFile">脚本路径,物理路径</param>
  111. /// <returns></returns>
  112. public bool Go(string strSql, CommandType commandType = CommandType.Text)
  113. {
  114.  
  115. this.Open();
  116.  
  117. try
  118. {
  119. using (SqlCommand cmd = new SqlCommand()
  120. {
  121. CommandText = strSql,
  122. CommandType = commandType,
  123. Connection = this.Connection,
  124. })
  125. {
  126. if (this.Transaction != null)
  127. cmd.Transaction = this.Transaction;
  128.  
  129. foreach (string Sql in SqlList(strSql))
  130. {
  131. cmd.CommandText = Sql;
  132. cmd.ExecuteNonQuery();
  133. }
  134. }
  135. return true;
  136. }
  137. catch
  138. {
  139. if (this.AutoRollback != AutoRollback.None)
  140. this.RollbackTrans();
  141. throw;
  142. }
  143. }
  144. private static string[] SqlList(string StrSql)
  145. {
  146. string[] _strList = StrSql.Split(new string[] { "GO" }, StringSplitOptions.RemoveEmptyEntries);
  147. return _strList;
  148. }
  149. #endregion
  150. /// <summary>
  151. /// 执行SQL语句, 此方法用于插入、更新操作
  152. /// 返回受影响的行数
  153. /// </summary>
  154. /// <param name="text">SQL执行语句</param>
  155. /// <param name="commandType">语句类型</param>
  156. /// <param name="args">语句参数</param>
  157. /// <returns>返回受影响的行数</returns>
  158. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
  159. public int Execute(
  160. string text,
  161. CommandType commandType = CommandType.Text,
  162. params SqlParameter[] args)
  163. {
  164. this.Open();
  165.  
  166. try
  167. {
  168. using (SqlCommand cmd = new SqlCommand()
  169. {
  170. CommandText = text,
  171. CommandType = commandType,
  172. Connection = this.Connection,
  173. })
  174. {
  175. if (this.Transaction != null)
  176. cmd.Transaction = this.Transaction;
  177.  
  178. AddParameterToCommand(cmd, args);
  179. return cmd.ExecuteNonQuery();
  180. }
  181.  
  182. }
  183. catch
  184. {
  185. if (this.AutoRollback != AutoRollback.None)
  186. this.RollbackTrans();
  187. throw;
  188. }
  189. }
  190.  
  191. /// <summary>
  192. /// SqlBulkCopy 大批量数据插入
  193. /// </summary>
  194. /// <param name="table">内存表 Datatable</param>
  195. /// <param name="destinationTableName">服务器上表的名称</param>
  196. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
  197. public void ExecuteBulkCopy(DataTable table,
  198. string destinationTableName
  199. )
  200. {
  201. this.BeginTrans();
  202. try
  203. {
  204. using (SqlBulkCopy copy = new SqlBulkCopy(Connection, SqlBulkCopyOptions.Default, this.Transaction))
  205. {
  206. copy.DestinationTableName = destinationTableName;
  207. for (int i = ; i < table.Columns.Count; i++)
  208. {
  209. copy.ColumnMappings.Add(table.Columns[i].ColumnName, table.Columns[i].ColumnName);
  210. }
  211. copy.WriteToServer(table);
  212. this.CommitTrans();
  213. }
  214. }
  215. catch
  216. {
  217. if (this.AutoRollback != AutoRollback.None)
  218. this.RollbackTrans();
  219. throw;
  220. }
  221. }
  222.  
  223. /// <summary>
  224. /// 执行SQL语句,并返回查询结果的第一行第一列的值要返回什么样的值,就T 里面写入什么类型
  225. /// </summary>
  226. /// <typeparam name="T">返回结果类型</typeparam>
  227. /// <param name="query">SQL语句</param>
  228. /// <param name="commandType">语句类型</param>
  229. /// <param name="args">语句参数</param>
  230. /// <returns>返回查询结果的第一行第一列的值</returns>
  231. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
  232. public T ExecuteScalar<T>(
  233. string query,
  234. CommandType commandType = CommandType.Text,
  235. params SqlParameter[] args)
  236. {
  237. this.Open();
  238.  
  239. try
  240. {
  241. using (SqlCommand cmd = new SqlCommand()
  242. {
  243. CommandText = query,
  244. CommandType = commandType,
  245. Connection = this.Connection,
  246. })
  247. {
  248. if (this.Transaction != null)
  249. cmd.Transaction = this.Transaction;
  250.  
  251. AddParameterToCommand(cmd, args);
  252. object obj = cmd.ExecuteScalar();
  253. if (obj == null || obj == DBNull.Value)
  254. return default(T);
  255. return (T)obj;
  256. }
  257. }
  258. catch
  259. {
  260. if (this.AutoRollback != AutoRollback.None)
  261. this.RollbackTrans();
  262. throw;
  263. }
  264. }
  265.  
  266. /// <summary>
  267. /// 执行SQL语句,并返回查询结果的第一行第一列的值
  268. /// </summary>
  269. /// <typeparam name="T">返回结果类型</typeparam>
  270. /// <param name="query">SQL语句</param>
  271. /// <param name="commandType">语句类型</param>
  272. /// <param name="args">语句参数</param>
  273. /// <returns>返回查询结果的第一行第一列的值</returns>
  274. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
  275. public int ExecuteScalar(
  276. string query,
  277. CommandType commandType = CommandType.Text,
  278. params SqlParameter[] args)
  279. {
  280. this.Open();
  281.  
  282. try
  283. {
  284. using (SqlCommand cmd = new SqlCommand()
  285. {
  286. CommandText = query,
  287. CommandType = commandType,
  288. Connection = this.Connection,
  289. })
  290. {
  291. if (this.Transaction != null)
  292. cmd.Transaction = this.Transaction;
  293.  
  294. AddParameterToCommand(cmd, args);
  295. object obj = cmd.ExecuteScalar();
  296. return Convert.ToInt32(obj);
  297. }
  298. }
  299. catch
  300. {
  301. if (this.AutoRollback != AutoRollback.None)
  302. this.RollbackTrans();
  303. throw;
  304. }
  305. }
  306.  
  307. /// <summary>
  308. /// 执行SQL语句,并返回查询结果的实体类集合
  309. /// 实体类的属性需包含查询结果的表头
  310. /// </summary>
  311. /// <typeparam name="T">查询结果的实体类</typeparam>
  312. /// <param name="query">SQL语句</param>
  313. /// <param name="commandType">语句类型</param>
  314. /// <param name="args">语句参数</param>
  315. /// <returns>返回结果的实体类集合</returns>
  316. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
  317. public List<T> Query<T>(
  318. string query,
  319. CommandType commandType = CommandType.Text,
  320. params SqlParameter[] args)
  321. where T : new()
  322. {
  323. this.Open();
  324.  
  325. try
  326. {
  327. using (SqlCommand cmd = new SqlCommand()
  328. {
  329. CommandText = query,
  330. CommandType = commandType,
  331. Connection = this.Connection,
  332. })
  333. {
  334. if (this.Transaction != null)
  335. cmd.Transaction = this.Transaction;
  336.  
  337. AddParameterToCommand(cmd, args);
  338. using (SqlDataReader reader = cmd.ExecuteReader())
  339. {
  340. List<T> result = new List<T>();
  341. var columns = GetColumns<T>(reader);
  342. while (reader.Read())
  343. {
  344. T obj = CreateObject<T>(reader, columns);
  345. result.Add(obj);
  346. }
  347. return result;
  348. }
  349. }
  350. }
  351. catch
  352. {
  353. if (AutoRollback == AutoRollback.Always)
  354. this.RollbackTrans();
  355. throw;
  356. }
  357. }
  358.  
  359. /// <summary>
  360. /// 执行SQL语句,返回 SqlDataReader
  361. /// </summary>
  362. /// <param name="query">SQL语句</param>
  363. /// <param name="commandType">语句类型</param>
  364. /// <param name="args">语句参数</param>
  365. /// <returns>SqlDataReader</returns>
  366. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
  367. public SqlDataReader GetDataReader(
  368. string query,
  369. CommandType commandType = CommandType.Text,
  370. params SqlParameter[] args)
  371. {
  372. this.Open();
  373.  
  374. try
  375. {
  376. using (SqlCommand cmd = new SqlCommand()
  377. {
  378. CommandText = query,
  379. CommandType = commandType,
  380. Connection = this.Connection,
  381. })
  382. {
  383. if (this.Transaction != null)
  384. cmd.Transaction = this.Transaction;
  385.  
  386. AddParameterToCommand(cmd, args);
  387. return cmd.ExecuteReader();
  388. }
  389. }
  390. catch
  391. {
  392. if (AutoRollback == AutoRollback.Always)
  393. this.RollbackTrans();
  394. throw;
  395. }
  396. }
  397.  
  398. /// <summary>
  399. /// 执行SQL语句,以DataTable对象作为结果返回查询结果
  400. /// </summary>
  401. /// <param name="query">SQL语句</param>
  402. /// <param name="commandType">语句类型</param>
  403. /// <param name="args">语句参数</param>
  404. /// <returns>DataTable对象</returns>
  405. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
  406. public DataTable QueryDT(
  407. string query,
  408. CommandType commandType = CommandType.Text,
  409. params SqlParameter[] args)
  410. {
  411. this.Open();
  412. try
  413. {
  414. using (SqlCommand cmd = new SqlCommand()
  415. {
  416. CommandText = query,
  417. CommandType = commandType,
  418. Connection = this.Connection,
  419. })
  420. {
  421. if (this.Transaction != null)
  422. cmd.Transaction = this.Transaction;
  423.  
  424. AddParameterToCommand(cmd, args);
  425. DataTable result = new DataTable();
  426. using (SqlDataAdapter ad = new SqlDataAdapter())
  427. {
  428. ad.SelectCommand = cmd;
  429. ad.Fill(result);
  430. return result;
  431. }
  432. }
  433. }
  434. catch
  435. {
  436. if (AutoRollback == AutoRollback.Always)
  437. this.RollbackTrans();
  438. throw;
  439. }
  440. }
  441.  
  442. /// <summary>
  443. /// 执行SQL语句,并返回查询结果的第一个对象, 如果没有查询结果则为NULL
  444. /// 实体类的属性需包含查询结果的表头
  445. /// </summary>
  446. /// <typeparam name="T">查询结果的实体类</typeparam>
  447. /// <param name="query">SQL语句</param>
  448. /// <param name="commandType">语句类型</param>
  449. /// <param name="args">语句参数</param>
  450. /// <returns>查询结果的第一个对象,如果没有查询结果则为NULL</returns>
  451. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:检查 SQL 查询是否存在安全漏洞")]
  452. public T FirstOrDefault<T>(
  453. string query,
  454. CommandType commandType = CommandType.Text,
  455. params SqlParameter[] args)
  456. where T : new()
  457. {
  458. this.Open();
  459.  
  460. try
  461. {
  462. using (SqlCommand cmd = new SqlCommand()
  463. {
  464. CommandText = query,
  465. CommandType = commandType,
  466. Connection = this.Connection,
  467. })
  468. {
  469. if (this.Transaction != null)
  470. cmd.Transaction = this.Transaction;
  471.  
  472. AddParameterToCommand(cmd, args);
  473.  
  474. using (SqlDataReader reader = cmd.ExecuteReader())
  475. {
  476. if (reader.HasRows)
  477. {
  478. var columns = GetColumns<T>(reader);
  479. reader.Read();
  480. return CreateObject<T>(reader, columns);
  481. }
  482.  
  483. return default(T);
  484. }
  485. }
  486. }
  487. catch
  488. {
  489. if (AutoRollback == AutoRollback.Always)
  490. this.RollbackTrans();
  491. throw;
  492. }
  493. }
  494. #endregion
  495.  
  496. #region HelperMethods
  497. public void Open()
  498. {
  499. if (this.Connection != null &&
  500. this.Connection.State != ConnectionState.Open)
  501. this.Connection.Open();
  502. }
  503.  
  504. public void Close()
  505. {
  506. if (this.Connection != null)
  507. this.Connection.Close();
  508. }
  509.  
  510. public SqlCommand CreateCommand()
  511. {
  512. SqlCommand cmd = new SqlCommand();
  513. cmd.Connection = this.Connection;
  514. if (this.Transaction != null)
  515. cmd.Transaction = this.Transaction;
  516.  
  517. return cmd;
  518. }
  519.  
  520. public static void AddParameterToCommand(SqlCommand cmd, SqlParameter[] args)
  521. {
  522. if (args != null && args.Length > )
  523. {
  524. foreach (var arg in args)
  525. {
  526. if (arg != null)
  527. {
  528. if (arg.IsNullable && arg.Value == null)
  529. {
  530. arg.Value = DBNull.Value;
  531. }
  532.  
  533. cmd.Parameters.Add(arg);
  534. }
  535. }
  536. }
  537. }
  538.  
  539. private static PropertyInfo[] GetColumns<T>(SqlDataReader reader)
  540. {
  541. List<T> result = new List<T>();
  542. Type type = typeof(T);
  543. var columns = new List<PropertyInfo>(reader.FieldCount);
  544. var props = type.GetProperties();
  545. string name;
  546.  
  547. for (int i = ; i < reader.FieldCount; i++)
  548. {
  549. name = reader.GetName(i);
  550. for (int j = ; j < props.Length; j++)
  551. {
  552. if (props[j].Name.ToLower() == name.ToLower())
  553. {
  554. columns.Add(props[j]);
  555. break;
  556. }
  557. }
  558. }
  559.  
  560. return columns.ToArray();
  561. }
  562.  
  563. private static T CreateObject<T>(SqlDataReader reader, PropertyInfo[] columns) where T : new()
  564. {
  565. T result = Activator.CreateInstance<T>();
  566. for (int i = ; i < columns.Length; i++)
  567. {
  568. columns[i].SetValue(result, reader[columns[i].Name] == DBNull.Value ? null : reader[columns[i].Name], null);
  569. }
  570.  
  571. return result;
  572. }
  573. #endregion
  574.  
  575. }
  576. }

C# sql Helper的更多相关文章

  1. 微软原版SQL Helper

    代码 Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-- ...

  2. Java sql helper[转]

    原文:http://www.cnblogs.com/beijiguangyong/archive/2011/12/10/2302737.html package sql; import java.sq ...

  3. sql helper

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.C ...

  4. [Android 开发教程(1)]-- Saving Data in SQL Databases

    Saving data to a database is ideal for repeating or structured data, such as contact information. Th ...

  5. Android学习笔记——保存数据到SQL数据库中(Saving Data in SQL Databases)

    知识点: 1.使用SQL Helper创建数据库 2.数据的增删查改(PRDU:Put.Read.Delete.Update) 背景知识: 上篇文章学习了保存文件,今天学习的是保存数据到SQL数据库中 ...

  6. 数据库Error:The ScriptCollection in ScriptName not find

    System.InvalidOperationException: The ScriptCollection in ScriptName not find 在 WMI.SQL.HELPER.CONFI ...

  7. java攻城狮之路(Android篇)--ListView与ContentProvider

    一.ListView 1.三种Adapter构建ListView ListView添加条目的时候, 可以使用setAdapter(ListAdapter)方法, 常用的ListAdapter有三种 B ...

  8. java攻城狮之路(Android篇)--SQLite

    一.Junit    1.怎么使用        在AndroidManifest.xml文件中进行配置, 在manifest借点下配置instrumentation, 在application借点下 ...

  9. Oracle 数据库中不同事务并发访问的问题

    现象 以SQL/Helper为例,打开不同的SQL窗口,对同一个表格进行操作,如下所示. 窗口1:当执行更新任务.紧接着执行查询时获得一组查询结果.结果是对的. 窗口2:而在另外一个SQL查询窗口中执 ...

随机推荐

  1. ASP.NET MVC3快速入门——第四节、添加一个模型

    在本节中我们将追加一些类来管理数据库中的电影.这些类将成为我们的MVC应用程序中的“模型”部分.我们将使用一个.NET Framework的被称之为“Entiry Framework”的数据访问技术来 ...

  2. AT89C 系列单片机解密原理

    单片机解密简单就是擦除单片机片内的加密锁定位.由于AT89C系列单片机擦除操作时序设计上的不合理.使在擦除片内程序之前首先擦除加密锁定位成为可能.AT89C系列单片机擦除操作的时序为:擦除开始---- ...

  3. java获得指定日期的前一天,后一天的代码

    /** * 获得指定日期的前一天 * @param specifiedDay * @return * @throws Exception */ public static String getSpec ...

  4. haporxy 负载elasticsearch

    <pre name="code" class="html">-bash-4.1# cat /etc/haproxy/haproxy.cfg glob ...

  5. linux svn用法

    创建一个版本库.项目目录. 创建一个版本库: svnadmin create ~/SVNTestRepo 创建一个项目目录: svn mkdir file:///home/lsf/SVNTestRep ...

  6. bzoj2243-染色(动态树lct)

    解析:增加三个变量lc(最左边的颜色),rc(最右边的颜色),sum(连续相同颜色区间段数).然后就是区间合并的搞法.我就不详细解释了,估计你已经想到 如何做了. 代码 #include<cst ...

  7. Java学习作业(14.4.21)

    前三次作业都是基础语法.真的好水啊.从这次开始记录. 1.编写Java程序,把当前目录下扩展名为txt的文件的扩展名全部更名为back. import java.io.*; import java.l ...

  8. 把一个select查询结果插入到一个表(可选指定字段和值实例)

    把一个select查询结果插入到一个表(可选指定字段和值实例) insert into  bak (cc,yf) select cc,9 from ket insert into bak (cc,yf ...

  9. 为github帐号添加SSH keys

    为github帐号添加SSH keys 2012-05-26 00:05 34279人阅读 评论(6) 收藏 举报 ssh文本编辑gitvim工具up 使用git clone命令从github上同步g ...

  10. nodejs报错 events.js:72 throw er; // Unhandled 'error' event

    var http = require('http'); var handlerRequest = function(req,res){ res.end('hello');}; var webServe ...