我是JSON和SQLBulkCopy的新手。我有一个JSON格式的POST数据,我想使用C#在Microsoft SQL中进行批量复制/插入。
JSON格式:
{
"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/"
}]
}
类:
public class UrlData
{
public List<Url> URLs {get;set;}
}
public class Url
{
public string url_address {get;set;}
public string url_name {get;set;}
}
我如何有效地做到这一点?
由于您只需要加载
从10到50个网址显然不需要使用
SqlBulkCopy
-它用于数千个插入。除非您需要多次重复此操作。
因此,如果您有一个URL列表,即List,那么只需遍历列表中的所有URL并将它们插入数据库,例如
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();
}
但是,如果确实需要使用SqlBulkCopy
,则需要将类的对象转换URL
为DataTable
。为此,请看Marc Gravell的答案:
这是使用NuGet的FastMember进行的2013年不错的更新:
IEnumerable<SomeType> data = ... DataTable table = new DataTable(); using(var reader = ObjectReader.Create(data)) { table.Load(reader); }
是的,这与这一点恰恰相反。反射就足够了-或者如果您需要更快,则
HyperDescriptor
在2.0或Expression
3.5中。实际上,HyperDescriptor
应该绰绰有余。例如:
// 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; }
所以,你可以用马克的解决方案之一,以创建DataTable
从你的List<URL>
。然后,您只需要将表写入服务器上的目标表即可:
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);
}
希望能帮助到你。
UPD
当然可以,因为BulkCopy只是作为插入命令而工作,但是它有点不同,仅此而已。我建议您使用中间表,以防操作极有可能出错(并且您希望尽可能少地忙于目标表)或需要进行一些数据转换,但前提是您需要它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句