BulkCopyExtensions.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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, bool needCommit = true)
  95. {
  96. bool result = true;
  97. if (conn.State == ConnectionState.Closed)
  98. {
  99. conn.Open();
  100. }
  101. var stran = conn.BeginTransaction();
  102. try
  103. {
  104. using (SqlBulkCopy bcp = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, stran))
  105. {
  106. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  107. bcp.DestinationTableName = dt.TableName;
  108. bcp.WriteToServer(dt);
  109. if (needCommit)
  110. {
  111. stran.Commit();
  112. }
  113. }
  114. }
  115. catch (Exception ex)
  116. {
  117. result = false;
  118. stran.Rollback();
  119. throw ex;
  120. }
  121. //finally
  122. //{
  123. // conn.Close();
  124. //}
  125. return result;
  126. }
  127. /// <summary>
  128. /// 带事务的bcp方式批量插入数据库操作(注意要指定TableName属性)。
  129. /// </summary>
  130. /// <param name="conn"></param>
  131. /// <param name="dt"></param>
  132. /// <returns></returns>
  133. public static bool ExecuteBulkCopy(SqlConnection conn, SqlTransaction stran, DataTable dt)
  134. {
  135. bool result = true;
  136. try
  137. {
  138. using (SqlBulkCopy bcp = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, stran))
  139. {
  140. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  141. bcp.DestinationTableName = dt.TableName;
  142. bcp.WriteToServer(dt);
  143. }
  144. }
  145. catch (Exception ex)
  146. {
  147. result = false;
  148. string err = ex.Message;
  149. throw ex;
  150. }
  151. return result;
  152. }
  153. public static void BluckTable(SqlConnection conn, params DataTable[] blukParams)
  154. {
  155. if (conn.State == ConnectionState.Closed)
  156. {
  157. conn.Open();
  158. }
  159. var stran = conn.BeginTransaction();
  160. try
  161. {
  162. using (SqlBulkCopy bcp = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, stran))
  163. {
  164. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  165. foreach (var bluck in blukParams)
  166. {
  167. Bowin.Common.Linq.BulkCopyExtensions.ExecuteBulkCopy(conn, stran, bluck);
  168. }
  169. stran.Commit();
  170. }
  171. }
  172. catch (Exception ex)
  173. {
  174. stran.Rollback();
  175. throw ex;
  176. }
  177. //finally
  178. //{
  179. // conn.Close();
  180. //}
  181. }
  182. /// <summary>
  183. /// 将序列的数据插入到临时表中
  184. /// </summary>
  185. /// <param name="tempTableName">临时表名称,包括前面的#号</param>
  186. /// <param name="dataSource">任意可枚举数据源</param>
  187. /// <param name="singleColumnName">若为简单类型的列表,需指定临时表中的字段名</param>
  188. /// <remarks>必须将该方法在显式事务中调用,否则无法保证临时表的有效性</remarks>
  189. public static void BulkCopyToTempTable<T>(this SqlConnection conn, string tempTableName, IEnumerable<T> dataSource, string singleColumnName = "")
  190. {
  191. DataTable dt;
  192. if (singleColumnName == "")
  193. {
  194. dt = dataSource.ToTable(true);
  195. }
  196. else
  197. {
  198. dt = new DataTable("dataResult");
  199. var columnType = typeof(T);
  200. if (columnType.FullName.StartsWith("System.Nullable"))
  201. {
  202. columnType = ((System.Type)(typeof(T))).GetGenericArguments()[0];
  203. }
  204. dt.Columns.Add(singleColumnName, columnType);
  205. foreach (var data in dataSource)
  206. {
  207. var row = dt.NewRow();
  208. if (data != null)
  209. {
  210. row[singleColumnName] = data;
  211. }
  212. else
  213. {
  214. row[singleColumnName] = DBNull.Value;
  215. }
  216. dt.Rows.Add(row);
  217. }
  218. }
  219. string sql = "create table " + tempTableName + " (";
  220. if (singleColumnName != "")
  221. {
  222. //System.Data.Entity.Infrastructure.DbCompiledModel
  223. sql += "[" + singleColumnName + "] " + ConvertToDataTable.SqlDbTypeConvertor[typeof(T)];
  224. }
  225. else
  226. {
  227. foreach (DataColumn col in dt.Columns)
  228. {
  229. sql += "[" + col.ColumnName + "] " + ConvertToDataTable.SqlDbTypeConvertor[col.DataType] + ",";
  230. }
  231. sql = sql.TrimEnd(',');
  232. }
  233. sql += ")";
  234. if (conn.State == ConnectionState.Closed)
  235. {
  236. conn.Open();
  237. }
  238. SqlCommand comm = conn.CreateCommand();
  239. comm.CommandText = sql;
  240. comm.CommandTimeout = 6000;
  241. comm.ExecuteNonQuery();
  242. try
  243. {
  244. using (SqlBulkCopy bcp = new SqlBulkCopy(conn))
  245. {
  246. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  247. bcp.DestinationTableName = tempTableName;
  248. bcp.WriteToServer(dt);
  249. }
  250. }
  251. catch (Exception ex)
  252. {
  253. throw ex;
  254. }
  255. }
  256. /// <summary>
  257. /// 将序列的数据插入到临时表中
  258. /// </summary>
  259. /// <param name="tempTableName">临时表名称,包括前面的#号</param>
  260. /// <param name="dataSource">任意可枚举数据源</param>
  261. /// <param name="singleColumnName">若为简单类型的列表,需指定临时表中的字段名</param>
  262. /// <remarks>必须将该方法在显式事务中调用,否则无法保证临时表的有效性</remarks>
  263. public static void BulkCopyToTempTableWithTransation<T>(this SqlConnection conn, SqlTransaction tran, string tempTableName, IEnumerable<T> dataSource, string singleColumnName = "")
  264. {
  265. DataTable dt;
  266. if (singleColumnName == "")
  267. {
  268. dt = dataSource.ToTable(true);
  269. }
  270. else
  271. {
  272. dt = new DataTable("dataResult");
  273. var columnType = typeof(T);
  274. if (columnType.FullName.StartsWith("System.Nullable"))
  275. {
  276. columnType = ((System.Type)(typeof(T))).GetGenericArguments()[0];
  277. }
  278. dt.Columns.Add(singleColumnName, columnType);
  279. foreach (var data in dataSource)
  280. {
  281. var row = dt.NewRow();
  282. if (data != null)
  283. {
  284. row[singleColumnName] = data;
  285. }
  286. else
  287. {
  288. row[singleColumnName] = DBNull.Value;
  289. }
  290. dt.Rows.Add(row);
  291. }
  292. }
  293. string sql = "create table " + tempTableName + " (";
  294. if (singleColumnName != "")
  295. {
  296. sql += "[" + singleColumnName + "] " + ConvertToDataTable.SqlDbTypeConvertor[typeof(T)];
  297. }
  298. else
  299. {
  300. foreach (DataColumn col in dt.Columns)
  301. {
  302. sql += "[" + col.ColumnName + "] " + ConvertToDataTable.SqlDbTypeConvertor[col.DataType] + ",";
  303. }
  304. sql = sql.TrimEnd(',');
  305. }
  306. sql += ")";
  307. SqlCommand comm = new SqlCommand(sql, conn, tran);
  308. comm.CommandText = sql;
  309. comm.CommandTimeout = 6000;
  310. comm.ExecuteNonQuery();
  311. try
  312. {
  313. using (SqlBulkCopy bcp = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, tran))
  314. {
  315. bcp.BulkCopyTimeout = 3600; //默认值 30秒
  316. bcp.DestinationTableName = tempTableName;
  317. bcp.WriteToServer(dt);
  318. }
  319. }
  320. catch (Exception ex)
  321. {
  322. throw ex;
  323. }
  324. }
  325. }
  326. }