马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

Datatable批量导入到表

[复制链接]
查看2694 | 回复0 | 2019-8-15 09:15:26 | 显示全部楼层 |阅读模式

封装批量提交数据到表,用于数据同步作业

  1. private string GetSelectFieldNames(DataTable dataTable, string tableName = "", string strwhere = "")
  2. {
  3. if (dataTable == null || dataTable.Columns.Count == 0)
  4. {
  5. return "";
  6. }
  7. if (tableName.NotHasValue())
  8. {
  9. tableName = dataTable.TableName;
  10. }
  11. var columns = (from DataColumn column in dataTable.Columns select column.ColumnName).ToList();
  12. string strColumns = string.Join(",", columns);
  13. string strSql = string.Format("select {0} from {1} {2}", strColumns, tableName, strwhere);
  14. return strSql;
  15. }
  16. /// <summary>
  17. /// 批量全表数据同步
  18. /// 该种方式可以支持报错情况下详细的字段错误信息
  19. /// </summary>
  20. /// <param name="dataTable"></param>
  21. /// <param name="toTableName"></param>
  22. /// <returns></returns>
  23. public bool BulkCopyToDataTable(DataTable dataTable, string toTableName = "")
  24. {
  25. if (dataTable == null || dataTable.Rows.Count == 0)
  26. {
  27. Tools.Debug("提交的表为空");
  28. return true;
  29. }
  30. if (toTableName.NotHasValue())
  31. {
  32. toTableName = dataTable.TableName;
  33. }
  34. Tools.Debug("一共提交" + dataTable.Rows.Count + "条数据到" + toTableName);
  35. using (var connection = new SqlConnection(DbConnectionString))
  36. {
  37. string strSelectSql = GetSelectFieldNames(dataTable, toTableName, "where 1=2");
  38. SqlTransaction tran =null;
  39. try
  40. {
  41. connection.Open();
  42. var newDatatable = new DataTable();
  43. using (var myDataAdapter = new SqlDataAdapter(strSelectSql, connection))
  44. {
  45. myDataAdapter.Fill(newDatatable);
  46. for (int j = 0; j < dataTable.Rows.Count; j++)
  47. {
  48. newDatatable.Rows.Add(dataTable.Rows[j].ItemArray);
  49. }
  50. using (var sqlcommanBuilder = new SqlCommandBuilder(myDataAdapter))
  51. {
  52. tran = connection.BeginTransaction();
  53. myDataAdapter.SelectCommand.Transaction = tran;
  54. myDataAdapter.Update(newDatatable);
  55. tran.Commit();
  56. }
  57. myDataAdapter.Dispose();
  58. }
  59. }
  60. catch (SqlException ex)
  61. {
  62. if (tran != null) tran.Rollback();
  63. Tools.Debug(String.Format("同步平台表:{0} ,执行数据库:{1} ,报错: {2}", toTableName, DbConnectionString, ex.Message));
  64. Tools.Error(ex);
  65. return false;
  66. }
  67. }
  68. return true;
  69. }
复制代码

  


来源:https://www.cnblogs.com/songconglai/p/11355838.html
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则