C#使用SqlBulkCopy批量复制数据到数据表

本文实例讲述了C#使用SqlBulkCopy批量复制数据到数据表的方法。分享给大家供大家参考。具体实现方法如下:

使用 SqlBulkCopy 类只能向 SQL Server 表写入数据。但是,数据源不限于 SQL Server;可以使用任何数据源,只要数据可加载到 DataTable 实例或可使用 IDataReader 实例读取数据

1.使用Datatable作为数据源的方式:

下面的代码使用到了ColumnMappings,因为目标表和数据源Datatable的结构不一致,需要这么一个映射来指定对应关系

代码如下:

public string SaveJHCData(LzShopBasicData[] datas)
{
    var result = new AResult();
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["**"].ConnectionString);
    con.Open();
    foreach (var item in datas)
    {

Logger.Info("数据更新处理,店铺名称:" + item.ShopName + "数据日期" + item.SellDate);
 try
 {
     using (TransactionScope scope = new TransactionScope())
     {

DataTable JHCOrderItemsdt = SaveJHCOrderItemsData(item);
  SqlBulkCopy JHCOrderItemscopy = new SqlBulkCopy(con);
  JHCOrderItemscopy.ColumnMappings.Add("orderId", "orderId");
  JHCOrderItemscopy.ColumnMappings.Add("auctionId", "auctionId");
  JHCOrderItemscopy.ColumnMappings.Add("itemTitle", "itemTitle");
  JHCOrderItemscopy.ColumnMappings.Add("tradeAmt", "tradeAmt");
  JHCOrderItemscopy.ColumnMappings.Add("alipayNum", "alipayNum");
  JHCOrderItemscopy.ColumnMappings.Add("tradeTime", "tradeTime");
  JHCOrderItemscopy.ColumnMappings.Add("uv", "uv");
  JHCOrderItemscopy.ColumnMappings.Add("srcId", "srcId");
  JHCOrderItemscopy.ColumnMappings.Add("srcName", "srcName");
  JHCOrderItemscopy.ColumnMappings.Add("DataType", "DataType");
  JHCOrderItemscopy.ColumnMappings.Add("DataDate", "DataDate");
  JHCOrderItemscopy.ColumnMappings.Add("OrderSourceID", "OrderSourceID");
  JHCOrderItemscopy.ColumnMappings.Add("ShopName", "ShopName");
  JHCOrderItemscopy.DestinationTableName = "JHCOrderItems";
  JHCOrderItemscopy.WriteToServer(JHCOrderItemsdt);
  result.Updatedata += 1;
  result.UpdatedataText += item.SellDate + ",";
  scope.Complete();
  Logger.Info(item.SellDate + "事务提交");
     }
 }
 catch (Exception ex)
 {
     Logger.Error(ex.ToString());
     continue;
 }
    }
    con.Close();
    return result.ToSerializeObject();
}

2.使用IDataReader作为数据源的方式,这种方式个人认为用的很少,首先目标表和来源表两个数据库连接你都需要拿到,如果两个都可以拿到,一般直接操作sql就可以解决:

这里是直接拷贝的MSDN的代码,

用到的AdventureWorks数据库可以直接在网上下载到,下载地址如下:http://msftdbprodsamples.codeplex.com/releases

代码如下:

using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = GetConnectionString();
        // Open a sourceConnection to the AdventureWorks database.
        using (SqlConnection sourceConnection =
                   new SqlConnection(connectionString))
        {
            sourceConnection.Open();

// Perform an initial count on the destination table.
            SqlCommand commandRowCount = new SqlCommand(
                "SELECT COUNT(*) FROM " +
                "dbo.BulkCopyDemoMatchingColumns;",
                sourceConnection);
            long countStart = System.Convert.ToInt32(
                commandRowCount.ExecuteScalar());
            Console.WriteLine("Starting row count = {0}", countStart);

// Get data from the source table as a SqlDataReader.
            SqlCommand commandSourceData = new SqlCommand(
                "SELECT ProductID, Name, " +
                "ProductNumber " +
                "FROM Production.Product;", sourceConnection);
            SqlDataReader reader =
                commandSourceData.ExecuteReader();

// Open the destination connection. In the real world you would
            // not use SqlBulkCopy to move data from one table to the other
            // in the same database. This is for demonstration purposes only.
            using (SqlConnection destinationConnection =
                       new SqlConnection(connectionString))
            {
                destinationConnection.Open();

// Set up the bulk copy object.
                // Note that the column positions in the source
                // data reader match the column positions in
                // the destination table so there is no need to
                // map columns.
                using (SqlBulkCopy bulkCopy =
                           new SqlBulkCopy(destinationConnection))
                {
                    bulkCopy.DestinationTableName =
                        "dbo.BulkCopyDemoMatchingColumns";

try
                    {
                        // Write from the source to the destination.
                        bulkCopy.WriteToServer(reader);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    finally
                    {
                        // Close the SqlDataReader. The SqlBulkCopy
                        // object is automatically closed at the end
                        // of the using block.
                        reader.Close();
                    }
                }

// Perform a final count on the destination
                // table to see how many rows were added.
                long countEnd = System.Convert.ToInt32(
                    commandRowCount.ExecuteScalar());
                Console.WriteLine("Ending row count = {0}", countEnd);
                Console.WriteLine("{0} rows were added.", countEnd - countStart);
                Console.WriteLine("Press Enter to finish.");
                Console.ReadLine();
            }
        }
    }

private static string GetConnectionString()
        // To avoid storing the sourceConnection string in your code,
        // you can retrieve it from a configuration file.
    {
        return "Data Source=(local); " +
            " Integrated Security=true;" +
            "Initial Catalog=AdventureWorks;";
    }
}

实战:借助类型反射动态构建Datatable数据源,通过SqlBulkCopy批量保存入库

1.获取一张空的Datatable:

代码如下:

var dt = bisdal.From<TopBrand>(TopBrand._.ID == -1, OrderByClip.Default).ToDataTable();

2.填充DataTable,这里是通过遍历外部的集合,把属性属性逐一赋值填充到目标Datatable

代码如下:

foreach (var item in brandselldataitems)
{
 try
 {

TopBrand topbrand = new TopBrand
     {
  BrandIndex = item.mk,
  BrandName = item.c58,
  Date = date,
  WinnerAmt = item.c60,
  WinnerPeople = item.c62,
  WinnerProNum = item.c61,
  HotTaobaoCategoryID = cid
     };
     CreateDtByItem<TopBrand>(topbrand, dt);
 }
 catch (Exception ex)
 {
     Logger.Error(ex.ToString());
     continue;
 }
}

这里借助反射,遍历实体属性集合,动态构建DataTableRow对象

代码如下:

private void CreateDtByItem<T>(T item, DataTable dt)
{
    System.Reflection.PropertyInfo[] properties = item.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
    var newrow = dt.NewRow();
    foreach (System.Reflection.PropertyInfo pitem in properties)
    {

string name = pitem.Name;
 if (name == "children")
 {
     continue;
 }
 object value = pitem.GetValue(item, null);
 newrow[name] = value == null ? DBNull.Value : value;
    }
    dt.Rows.Add(newrow);
}

3.保存入库:

代码如下:

BulkWriteToServer(con, "TopBrand", dt);

这里因为目标表和数据源的Datatable数据结构一致,所以省去了ColumnMappings列映射的操作,可以直接WriteToServer保存

代码如下:

private void BulkWriteToServer(SqlConnection con, string destinationtablename, DataTable sourcedt)
{
    try
    {
 if (con.State == ConnectionState.Closed)
 {
     con.Open();
 }
 SqlBulkCopy topbranddtcopy = new SqlBulkCopy(con);
 topbranddtcopy.DestinationTableName = destinationtablename;
 topbranddtcopy.WriteToServer(sourcedt);
 con.Close();
    }
    catch (Exception ex)
    {
 Logger.Error("批量新增数据:" + destinationtablename + "," + ex.ToString());
    }
}

完整调用代码:

代码如下:

private void CreateTopBrandData(int date, int cid, List<BrandSellDataItem> brandselldataitems)
{
    try
    {
 var dt = bisdal.From<TopBrand>(TopBrand._.ID == -1, OrderByClip.Default).ToDataTable();
 foreach (var item in brandselldataitems)
 {
     try
     {

TopBrand topbrand = new TopBrand
  {
      BrandIndex = item.mk,
      BrandName = item.c58,
      Date = date,
      WinnerAmt = item.c60,
      WinnerPeople = item.c62,
      WinnerProNum = item.c61,
      HotTaobaoCategoryID = cid
  };
  CreateDtByItem<TopBrand>(topbrand, dt);
     }
     catch (Exception ex)
     {
  Logger.Error(ex.ToString());
  continue;
     }
 }
 BulkWriteToServer(con, "TopBrand", dt);
    }
    catch (Exception ex)
    {
 throw new Exception("CreateTopBrandData:" + ex.ToString());
    }
}

希望本文所述对大家的C#程序设计有所帮助。

(0)

相关推荐

  • C#中调用MySQL存储过程的方法

    本文实例讲述了C#中调用MySQL存储过程的方法.分享给大家供大家参考.具体如下: 这段代码演示在 C# 程序中调用 MySQL 的存储过程,没有返回值,没有参数传递. MySqlConnection myConnection; myConnection = new MySqlConnection(); myConnection.ConnectionString = "database="+database+";server="+ server+";use

  • C#访问SQLServer增删改查代码实例

    一个专门实现访问sql server数据库增删改查的操作代码,分享给大家,具体内容如下 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data; usi

  • C#批量更新sql实例

    本文实例讲述了C#批量更新sql的方法,分享给大家供大家参考.具体方法如下: 要实现批量更新Card数据,主要有以下步骤: 1.首先建立数据库连接 2.把部分数据填充到Dataset中 3.修改Dataset中数据的值 4.更新Dataset 5.循环操作,具体操作过程见下面代码: 复制代码 代码如下: public void BatchUpdate(List<Card> list) {     using (SqlConnection conn = new SqlConnection(DbH

  • C#实现过滤sql特殊字符的方法集合

    本文实例讲述了C#实现过滤sql特殊字符的方法集合.分享给大家供大家参考,具体如下: 1. /// <summary> /// 过滤不安全的字符串 /// </summary> /// <param name="Str"></param> /// <returns></returns> public static string FilteSQLStr(string Str) { Str = Str.Replace(

  • C#访问SQL Server数据库的实现方法

    本文实例讲述了C#访问SQL Server数据库的实现方法.分享给大家供大家参考.具体如下: 这里介绍一下用C#访问SQL Server数据库.这里要涉及到几个类:SqlConnection类.SqlCommand类.SqlDataReader类. SqlConnection类用于建立与数据库的连接,SqlCommand类用于创建SQL命令,SqlDataReader对象是执行SqlCommand对象返回结果集的查询语句后的结果. 下面是部分代码: /*其中server表示服务器,"."

  • C#/.Net 中快速批量给SQLite数据库插入测试数据

    使用transaction: var stopwatch = new Stopwatch(); using (var cmd = new SQLiteCommand(db_con)) using (var transaction = db_con.BeginTransaction()) { stopwatch.Reset(); stopwatch.Start(); foreach (var item in sorted) { sql = string.Format("insert into db

  • C#实现SQL批量插入数据到表的方法

    本文实例讲述了C#实现SQL批量插入数据到表的方法.分享给大家供大家参考,具体如下: #region 帮助实例:SQL 批量插入数据 多种方法 /// <summary> /// SqlBulkCopy往数据库中批量插入数据 /// </summary> /// <param name="sourceDataTable">数据源表</param> /// <param name="targetTableName"

  • C#创建数据库及导入sql脚本的方法

    本文实例讲述了C#创建数据库及导入sql脚本的方法.分享给大家供大家参考,具体如下: C#创建数据库: /// <summary> /// 创建数据库 /// </summary> /// <param name="connStr">连接字符串</param> /// <param name="_strDBName">数据库名称</param> /// <returns></r

  • C#基于SQLiteHelper类似SqlHelper类实现存取Sqlite数据库的方法

    本文实例讲述了C#基于SQLiteHelper类似SqlHelper类实现存取Sqlite数据库的方法.分享给大家供大家参考.具体如下: 这个类不是我实现的,英文原文地址为http://www.eggheadcafe.com/articles/20050315.asp,这里修改了原文中分析sql语句参数的方法,将方法名修改为AttachParameters,将其修饰符修改为private,并直接传递command到这个方法,直接绑定参数到comand.修改后的代码如下 using System;

  • c#实现用SQL池,多线程定时批量执行SQL语句的方法

    在实际项目开发中,业务逻辑层的处理速度往往很快,特别是在开发Socket通信服务的时候,网络传输很快,但是一旦加上数据库操作,性能一落千丈,数据库操作的效率往往成为一个系统整体性能的瓶颈.面对这问题,我们怎么办呢?好,下面我就为大家介绍一种方法:构建SQL池,分离业务逻辑层和数据访问层,让业务逻辑层从低效的数据库操作解脱,以提高系统整体性能. (一)SQL池 SQL池是SQL容器,用于存放业务逻辑层抛过来的SQL语句.SQL池主要提供以下几种方法: 1)internal string Pop()

随机推荐