• Datatable批量导入到表


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

    private string GetSelectFieldNames(DataTable dataTable, string tableName = "", string strwhere = "")
    {
    if (dataTable == null || dataTable.Columns.Count == 0)
    {
    return "";
    }
    if (tableName.NotHasValue())
    {
    tableName = dataTable.TableName;
    }
    var columns = (from DataColumn column in dataTable.Columns select column.ColumnName).ToList();
    
    string strColumns = string.Join(",", columns);
    string strSql = string.Format("select {0} from {1} {2}", strColumns, tableName, strwhere);
    return strSql;
    }
    
    /// <summary>
    /// 批量全表数据同步
    /// 该种方式可以支持报错情况下详细的字段错误信息
    /// </summary>
    /// <param name="dataTable"></param>
    /// <param name="toTableName"></param>
    /// <returns></returns>
    public bool BulkCopyToDataTable(DataTable dataTable, string toTableName = "")
    {
    if (dataTable == null || dataTable.Rows.Count == 0)
    {
    Tools.Debug("提交的表为空");
    return true;
    }
    if (toTableName.NotHasValue())
    {
    toTableName = dataTable.TableName;
    }
    Tools.Debug("一共提交" + dataTable.Rows.Count + "条数据到" + toTableName);
    
    using (var connection = new SqlConnection(DbConnectionString))
    {
    
    string strSelectSql = GetSelectFieldNames(dataTable, toTableName, "where 1=2");
    SqlTransaction tran =null;
    try
    {
    connection.Open();
    var newDatatable = new DataTable();
    using (var myDataAdapter = new SqlDataAdapter(strSelectSql, connection)) 
    { 
    
    myDataAdapter.Fill(newDatatable);
    for (int j = 0; j < dataTable.Rows.Count; j++)
    {
    newDatatable.Rows.Add(dataTable.Rows[j].ItemArray);
    }
    
    using (var sqlcommanBuilder = new SqlCommandBuilder(myDataAdapter))
    {
    tran = connection.BeginTransaction();
    myDataAdapter.SelectCommand.Transaction = tran;
    myDataAdapter.Update(newDatatable);
    tran.Commit();
    }
    myDataAdapter.Dispose();
    }
    }
    catch (SqlException ex)
    {
    if (tran != null) tran.Rollback();
    Tools.Debug(String.Format("同步平台表:{0} ,执行数据库:{1} ,报错: {2}", toTableName, DbConnectionString, ex.Message));
    Tools.Error(ex);
    return false;
    }
    }
    return true;
    }
    

      

  • 相关阅读:
    springMVC+ajax分页查询
    SSM ( Spring 、 SpringMVC 和 Mybatis )配置详解
    Spring整合Hibernate详细步骤
    Spring AOP 注解和xml实现 --转载
    spring笔记--使用springAPI以及自定义类 实现AOP的一个例子
    SSH框架总结(框架分析+环境搭建+实例源码下载) 《转》
    对Spring的IoC和DI最生动的解释
    [转载]jQuery.extend 函数详解
    [转载]Request、Request.Form和Request.QueryString的区别
    [转载]用纯css改变下拉列表select框的默认样式
  • 原文地址:https://www.cnblogs.com/songconglai/p/11355838.html
Copyright © 2020-2023  润新知