BulkCopyExtensions.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data.SqlClient;
  6. using System.Data;
  7. using System.Collections;
  8. using System.Configuration;
  9. using Bowin.Common.Data;
  10. using Bowin.Common.Linq.DB;
  11. namespace Bowin.Common.Linq
  12. {
  13. public static class BulkCopyExtensions
  14. {
  15. public static bool ExecuteBulkCopy<T>(this IEnumerable<T> dataSource, string dbName, string tableName)
  16. where T : class
  17. {
  18. SqlConnection conn;
  19. if (SqlConnectionManager.IsGlobalConnectionStarted)
  20. {
  21. conn = SqlConnectionManager.GetConnection(dbName);
  22. }
  23. else
  24. {
  25. conn = new SqlConnection(ConfigurationManager.ConnectionStrings[dbName].ConnectionString);
  26. if (conn.State == ConnectionState.Closed)
  27. {
  28. conn.Open();
  29. }
  30. }
  31. try
  32. {
  33. var dt = dataSource.ToTable(true);
  34. dt.TableName = tableName;
  35. using (SqlBulkCopy bcp = new SqlBulkCopy(conn))
  36. {
  37. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  38. bcp.DestinationTableName = dt.TableName;
  39. bcp.WriteToServer(dt);
  40. }
  41. }
  42. catch (Exception ex)
  43. {
  44. throw (ex);
  45. //return false;
  46. }
  47. finally
  48. {
  49. if (!SqlConnectionManager.IsGlobalConnectionStarted)
  50. {
  51. conn.Close();
  52. }
  53. }
  54. return true;
  55. }
  56. public static bool ExecuteBulkCopy<T>(this IEnumerable<T> dataSource, SqlConnection db, string tableName)
  57. where T : class
  58. {
  59. try
  60. {
  61. var dt = dataSource.ToTable(true);
  62. dt.TableName = tableName;
  63. if (db.State == ConnectionState.Closed)
  64. {
  65. db.Open();
  66. }
  67. using (SqlBulkCopy bcp = new SqlBulkCopy(db))
  68. {
  69. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  70. bcp.DestinationTableName = dt.TableName;
  71. bcp.WriteToServer(dt);
  72. }
  73. return true;
  74. }
  75. catch (Exception ex)
  76. {
  77. throw (ex);
  78. //return false;
  79. }
  80. finally
  81. {
  82. if (!SqlConnectionManager.IsGlobalConnectionStarted)
  83. {
  84. db.Close();
  85. }
  86. }
  87. }
  88. /// <summary>
  89. /// 带事务的bcp方式批量插入数据库操作(注意要指定TableName属性)。
  90. /// </summary>
  91. /// <param name="conn"></param>
  92. /// <param name="dt"></param>
  93. /// <returns></returns>
  94. public static bool ExecuteBulkCopy(SqlConnection conn, DataTable dt)
  95. {
  96. bool result = true;
  97. if (conn.State == ConnectionState.Closed)
  98. {
  99. conn.Open();
  100. }
  101. try
  102. {
  103. using (SqlBulkCopy bcp = new SqlBulkCopy(conn))
  104. {
  105. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  106. bcp.DestinationTableName = dt.TableName;
  107. bcp.WriteToServer(dt);
  108. }
  109. }
  110. catch (Exception ex)
  111. {
  112. result = false;
  113. throw ex;
  114. }
  115. //finally
  116. //{
  117. // conn.Close();
  118. //}
  119. return result;
  120. }
  121. /// <summary>
  122. /// 带事务的bcp方式批量插入数据库操作(注意要指定TableName属性)。
  123. /// </summary>
  124. /// <param name="conn"></param>
  125. /// <param name="dt"></param>
  126. /// <returns></returns>
  127. public static bool ExecuteBulkCopy(SqlConnection conn, SqlTransaction stran, DataTable dt)
  128. {
  129. bool result = true;
  130. try
  131. {
  132. using (SqlBulkCopy bcp = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, stran))
  133. {
  134. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  135. bcp.DestinationTableName = dt.TableName;
  136. bcp.WriteToServer(dt);
  137. }
  138. }
  139. catch (Exception ex)
  140. {
  141. result = false;
  142. string err = ex.Message;
  143. throw ex;
  144. }
  145. return result;
  146. }
  147. public static void BluckTable(SqlConnection conn, params DataTable[] blukParams)
  148. {
  149. if (conn.State == ConnectionState.Closed)
  150. {
  151. conn.Open();
  152. }
  153. var stran = conn.BeginTransaction();
  154. try
  155. {
  156. using (SqlBulkCopy bcp = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, stran))
  157. {
  158. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  159. foreach (var bluck in blukParams)
  160. {
  161. Bowin.Common.Linq.BulkCopyExtensions.ExecuteBulkCopy(conn, stran, bluck);
  162. }
  163. stran.Commit();
  164. }
  165. }
  166. catch (Exception ex)
  167. {
  168. stran.Rollback();
  169. throw ex;
  170. }
  171. //finally
  172. //{
  173. // conn.Close();
  174. //}
  175. }
  176. /// <summary>
  177. /// 将序列的数据插入到临时表中
  178. /// </summary>
  179. /// <param name="tempTableName">临时表名称,包括前面的#号</param>
  180. /// <param name="dataSource">任意可枚举数据源</param>
  181. /// <param name="singleColumnName">若为简单类型的列表,需指定临时表中的字段名</param>
  182. /// <remarks>必须将该方法在显式事务中调用,否则无法保证临时表的有效性</remarks>
  183. public static void BulkCopyToTempTable<T>(this SqlConnection conn, string tempTableName, IEnumerable<T> dataSource, string singleColumnName = "")
  184. {
  185. DataTable dt;
  186. if (singleColumnName == "")
  187. {
  188. dt = dataSource.ToTable(true);
  189. }
  190. else
  191. {
  192. dt = new DataTable("dataResult");
  193. var columnType = typeof(T);
  194. if (columnType.FullName.StartsWith("System.Nullable"))
  195. {
  196. columnType = ((System.Type)(typeof(T))).GetGenericArguments()[0];
  197. }
  198. dt.Columns.Add(singleColumnName, columnType);
  199. foreach (var data in dataSource)
  200. {
  201. var row = dt.NewRow();
  202. if (data != null)
  203. {
  204. row[singleColumnName] = data;
  205. }
  206. else
  207. {
  208. row[singleColumnName] = DBNull.Value;
  209. }
  210. dt.Rows.Add(row);
  211. }
  212. }
  213. string sql = "create table " + tempTableName + " (";
  214. if (singleColumnName != "")
  215. {
  216. //System.Data.Entity.Infrastructure.DbCompiledModel
  217. sql += "[" + singleColumnName + "] " + ConvertToDataTable.SqlDbTypeConvertor[typeof(T)];
  218. }
  219. else
  220. {
  221. foreach (DataColumn col in dt.Columns)
  222. {
  223. sql += "[" + col.ColumnName + "] " + ConvertToDataTable.SqlDbTypeConvertor[col.DataType] + ",";
  224. }
  225. sql = sql.TrimEnd(',');
  226. }
  227. sql += ")";
  228. if (conn.State == ConnectionState.Closed)
  229. {
  230. conn.Open();
  231. }
  232. SqlCommand comm = conn.CreateCommand();
  233. comm.CommandText = sql;
  234. comm.CommandTimeout = 6000;
  235. comm.ExecuteNonQuery();
  236. try
  237. {
  238. using (SqlBulkCopy bcp = new SqlBulkCopy(conn))
  239. {
  240. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  241. bcp.DestinationTableName = tempTableName;
  242. bcp.WriteToServer(dt);
  243. }
  244. }
  245. catch (Exception ex)
  246. {
  247. throw ex;
  248. }
  249. }
  250. /// <summary>
  251. /// 将序列的数据插入到临时表中
  252. /// </summary>
  253. /// <param name="tempTableName">临时表名称,包括前面的#号</param>
  254. /// <param name="dataSource">任意可枚举数据源</param>
  255. /// <param name="singleColumnName">若为简单类型的列表,需指定临时表中的字段名</param>
  256. /// <remarks>必须将该方法在显式事务中调用,否则无法保证临时表的有效性</remarks>
  257. public static void BulkCopyToTempTableWithTransation<T>(this SqlConnection conn, SqlTransaction tran, string tempTableName, IEnumerable<T> dataSource, string singleColumnName = "")
  258. {
  259. DataTable dt;
  260. if (singleColumnName == "")
  261. {
  262. dt = dataSource.ToTable(true);
  263. }
  264. else
  265. {
  266. dt = new DataTable("dataResult");
  267. var columnType = typeof(T);
  268. if (columnType.FullName.StartsWith("System.Nullable"))
  269. {
  270. columnType = ((System.Type)(typeof(T))).GetGenericArguments()[0];
  271. }
  272. dt.Columns.Add(singleColumnName, columnType);
  273. foreach (var data in dataSource)
  274. {
  275. var row = dt.NewRow();
  276. if (data != null)
  277. {
  278. row[singleColumnName] = data;
  279. }
  280. else
  281. {
  282. row[singleColumnName] = DBNull.Value;
  283. }
  284. dt.Rows.Add(row);
  285. }
  286. }
  287. string sql = "create table " + tempTableName + " (";
  288. if (singleColumnName != "")
  289. {
  290. sql += "[" + singleColumnName + "] " + ConvertToDataTable.SqlDbTypeConvertor[typeof(T)];
  291. }
  292. else
  293. {
  294. foreach (DataColumn col in dt.Columns)
  295. {
  296. sql += "[" + col.ColumnName + "] " + ConvertToDataTable.SqlDbTypeConvertor[col.DataType] + ",";
  297. }
  298. sql = sql.TrimEnd(',');
  299. }
  300. sql += ")";
  301. SqlCommand comm = new SqlCommand(sql, conn, tran);
  302. comm.CommandText = sql;
  303. comm.CommandTimeout = 6000;
  304. comm.ExecuteNonQuery();
  305. try
  306. {
  307. using (SqlBulkCopy bcp = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, tran))
  308. {
  309. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  310. bcp.DestinationTableName = tempTableName;
  311. bcp.WriteToServer(dt);
  312. }
  313. }
  314. catch (Exception ex)
  315. {
  316. throw ex;
  317. }
  318. }
  319. }
  320. }