SQL批量复制/将在C# [英] Sql Bulk Copy/Insert in C#

查看:287
本文介绍了SQL批量复制/将在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的JSON和使用SqlBulkCopy。我有我想批量复制JSON格式的POST数据/在Microsoft SQL使用C#插入。

JSON格式:

  {
    网址:[{
        url_name:谷歌,
        url_address:http://www.google.com/
    },
    {
        url_name:雅虎,
        url_address:http://www.yahoo.com/
    },
    {
        url_name:FB,
        url_address:http://www.fb.com/
    },
    {
        url_name:MegaSearches,
        url_address:http://www.megasearches.com/
    }]
}
 

类:

 公共类UrlData
{
    公开名单< URL>网址{获取;集;}
}

公共类网址
{
    公共字符串url_address {获取;集;}
    公共字符串url_name {获取;集;}
}
 

我怎样才能做到这一点有效?

解决方案

既然你需要加载刚

从10到50网址
有明显没有必要使用使用SqlBulkCopy - 这是为成千上万的刀片。除非你需要重复此操作多次。

所以,如果你有一个网址列表,即列表,然后只需通过从列表中的所有URL循环,并把它们插入到数据库中,如:

 字符串insertQuery =插入TUrls(地址,姓名)值(@address,@name);
的foreach(在listOfUrls URL网址)
{
    的SqlCommand CMD =新的SqlCommand(insertQuery);
    cmd.Parameters.AddWithValue(@名,url.url_name);
    cmd.Parameters.AddWithValue(@地址,url.urld_address);

    //不要忘记带连接小心 - 我省略这部分的清晰度
    cmd.ExecuteNonQuery();
}
 


但是,如果你真的需要使用 SqlBulkCopy的 您需要将您的类的对象网​​址数据表。要做到这一点看看马克Gravell的回答

  

下面是一个使用一个不错的2013更新    FastMember 从的NuGet:

 的IEnumerable< SOMETYPE>数据= ...
数据表表=新的DataTable();
使用(VAR读卡器= ObjectReader.Create(数据)){
    table.Load(读卡器);
}
 

     


     

是的,这是pretty的许多<一个完全相反href="http://stackoverflow.com/questions/545328/asp-net-potential-memory-leaks-converting-datatable-to-lists/545429#545429">this一;   反思就够了 - 或者,如果你需要更快,    HyperDescriptor 在2.0,或者防爆pression 3.5。其实,    HyperDescriptor 应该是绰绰有余了。

     

例如:

  //删除这个如果不是在C#3.0 / .NET 3.5
公共静态数据表ToDataTable&LT; T&GT;(这个IList的&LT; T&GT;数据)
{
    PropertyDescriptorCollection道具=
        TypeDescriptor.GetProperties(typeof运算(T));
    数据表表=新的DataTable();
    的for(int i = 0; I&LT; props.Count;我++)
    {
        PropertyDescriptor与道具=道具[I]
        table.Columns.Add(prop.Name,prop.PropertyType);
    }
    对象[]值=新的对象[props.Count]
    的foreach(在数据T项)
    {
        的for(int i = 0; I&LT; values​​.Length;我++)
        {
            值[I] =道具[I] .GetValue(项目);
        }
        table.Rows.Add(值);
    }
    返回表;
}
 

所以,你可以使用马克的解决方案来创建数据表名单,其中,网址&GT; 。然后你只需要编写表到目标表的服务器:

 字符串csDestination =把这里的连接字符串到数据库;

使用(SqlConnection的destinationConnection =新的SqlConnection(csDestination))
使用(SqlBulkCopy的bulkCopy =新SqlBulkCopy的(destinationConnection))
{
    bulkCopy.DestinationTableName =TUrls;
    bulkCopy.WriteToServer(dataTableOfUrls);
}
 

希望它帮助。

UPD

  1. 答案为@ pseudonym27问题:你好,我可以使用BulkCopy类将数据附加到SQL数据库中现有的表

当然可以,因为BulkCopy工作方式只需插入命令,但确实也有一点点不同,仅此而已。我建议你​​使用中间表的情况下操作有很高的概率会出问题(你要忙你的目标表尽可能少的时间,可能的话),或者你需要做一些数据转换,但只有当你觉得需要吧。

I am new to JSON and SQLBulkCopy. I have a JSON formatted POST data that I want to Bulk Copy/Insert in Microsoft SQL using C#.

JSON Format:

{
    "URLs": [{
        "url_name": "Google",
        "url_address": "http://www.google.com/"
    },
    {
        "url_name": "Yahoo",
        "url_address": "http://www.yahoo.com/"
    },
    {
        "url_name": "FB",
        "url_address": "http://www.fb.com/"
    },
    {
        "url_name": "MegaSearches",
        "url_address": "http://www.megasearches.com/"
    }]
}

Classes:

public class UrlData
{
    public List<Url> URLs {get;set;}
}

public class Url
{
    public string url_address {get;set;}
    public string url_name {get;set;}
}

How can I do that efficiently?

解决方案

Since you need to load just

from 10 to 50 urls

there's obviously no need to use SqlBulkCopy - it's for thousands of inserts. Except if you'll be needed to repeat this operation many times.

So, if you have a list of urls, i.e. List, then just loop through all URL from list and insert them to database, e.g.

string insertQuery = "insert into TUrls(address, name) values(@address, @name)";
foreach (URL url in listOfUrls)
{
    SqlCommand cmd = new SqlCommand(insertQuery);
    cmd.Parameters.AddWithValue("@name", url.url_name);
    cmd.Parameters.AddWithValue("@address", url.urld_address);

    // don't forget to take care of connection - I omit this part for clearness
    cmd.ExecuteNonQuery();
}


But if you really need to use SqlBulkCopy you need to convert your objects of class URL to DataTable. To do this look at Marc Gravell's answer:

Here's a nice 2013 update using FastMember from NuGet:

IEnumerable<SomeType> data = ...
DataTable table = new DataTable();
using(var reader = ObjectReader.Create(data)) {
    table.Load(reader);
}


Yes, this is pretty much the exact opposite of this one; reflection would suffice - or if you need quicker, HyperDescriptor in 2.0, or maybe Expression in 3.5. Actually, HyperDescriptor should be more than adequate.

For example:

// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
        TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for(int i = 0 ; i < props.Count ; i++)
    {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;        
}

So you can use one of Marc's solutions to create DataTable from your List<URL>. Then you just need to write table to destination table on server:

string csDestination = "put here connection string to database";

using (SqlConnection destinationConnection = new SqlConnection(csDestination))
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))
{
    bulkCopy.DestinationTableName = "TUrls";
    bulkCopy.WriteToServer(dataTableOfUrls);
}

Hope it helps.

UPD

  1. Answer to @pseudonym27 question: "Hello can I use BulkCopy class to append data to existing table in SQL database?"

Of course you can, because BulkCopy works as just insert command, but does it a little bit different, that's all. I'd recommend you to use intermediate tables in case operation has high probability to go wrong (and you want to busy your destination table as little time as possible) or you need to do some data transformations, but only if you feel the need of it.

这篇关于SQL批量复制/将在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆