[英]Insert Dictionary elements into SQL table as rows using IDatareader and SqlBulkCopy
I need to improve dramatically the execution time of a process wich currently is just like this: 我需要极大地改善当前的进程的执行时间,如下所示:
private Dictionary<int, SingleElement> elements_buffer;
// ... Create and load values into "elements_buffer"
// (string, Datetime, double)
string query = "INSERT INTO Tests.dbo.test_table "
+ "(element_name,element_init,element_width) VALUES";
SingleElement element_aux;
for (int i = 0; i < MAX_ELEMS_IN_DICT; i++)
{
element_aux = elements_buffer[i];
query = query
+ "('"
+ element_aux.name
+ "','"
+ element_aux.init
+ "',"
+ element_aux.width
+ ")";
if (i < MAX_ELEMS_IN_DICT+1) {
query = query + ",";
}
}
// ... Execute the query
I was going to use Datatable
for the new version, but I've been reading about using SqlBulkCopy
together with IDatareader
, as mentioned in: 我打算将
Datatable
用于新版本,但我一直在阅读有关将SqlBulkCopy
与IDatareader
一起使用的IDatareader
,如以下所述:
SqlBulkCopy performance SqlBulkCopy性能
C# loops and mass insert C#循环和大量插入
It looks like to me a better choice for my code, but can't get to figure it out how to code it, though I would like to use it. 在我看来,对于我的代码来说,这是一个更好的选择,但是尽管我想使用它,但无法弄清楚如何编写代码。
Can I have some help with the translated code, please? 请给我有关翻译后代码的帮助吗?
Thanks in advance 提前致谢
As you already have figured out, you need to implement custom IDataReader . 如您所知,您需要实现自定义IDataReader 。 As your source is Dictionary - only few relatively simple method/properties such as int FieldCount, bool Read(), object Get(int i) should be implemented.
因为您的资料来源是Dictionary-仅应实现一些相对简单的方法/属性,例如int FieldCount,bool Read(),对象Get(int i)。
You may find useful examples ( a simple one ) of custom IDataReader implementations by googling sqlbulkcopy custom idatareader . 通过对sqlbulkcopy自定义idatareader进行谷歌搜索,可以找到自定义IDataReader实现的有用示例( 一个简单的例子)。
Also keep in mind that SqlBulkCopy ignores triggers, foreign keys and other constraints and is not able to handle exceptions. 还请记住,SqlBulkCopy会忽略触发器,外键和其他约束,并且无法处理异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.