[英]Using c# how to retrieve and update thousands of records from a SQL database efficiently
Process 处理
Questions 问题
What's the most efficient way to retrieve and store the data in Step 1? 在步骤1中检索和存储数据的最有效方法是什么? a. 一种。 Should I load this in a list string? 我应该将其加载到列表字符串中吗? b. b。 Do you recommend doing batches initially? 您是否建议先进行批处理?
What the most efficient way to achieve steps 2 and 3 什么是实现步骤2和3的最有效方法
To retrieve the 4M records you're going to want to use a SqlDataReader
- it only loads one row of data into memory at a time. 要检索4M记录,您将要使用SqlDataReader
一次仅将一行数据加载到内存中。
var cn = new SqlConnection("some connection string");
var cmd = new SqlCommand("SELECT ID FROM SomeTable", cn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
var id = reader.GetInt32(0);
// an so on
}
reader.Close();
reader.Dispose();
cn.Close();
Now, to handle two and three, I would leverage a DataTable
for the row you need to retrieve and then a SqlCommand
on the third database. 现在,要处理两个和三个,我将在需要检索的行上使用一个DataTable
,然后在第三个数据库上使用一个SqlCommand
。 This means that inside the reader.Read()
you can get the one row you need by filling a DataTable
with a SqlDataAdapter
and the issuing an ExecNonQuery
against a SqlCommand
for the UPDATE
statement. 这意味着在reader.Read()
内部,您可以通过用SqlDataAdapter
填充DataTable
并针对UPDATE
语句针对SqlCommand
发出ExecNonQuery
来获得所需的一行。
Another way of writing the above, and it's a bit safer, is to use the using
statement: 编写上述内容的另一种方法(更安全一些)是使用using
语句:
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var id = reader.GetInt32(0);
// an so on
}
}
that will eliminate the need for: 这将消除以下需求:
reader.Close();
reader.Dispose();
and so you could also issue that for the SqlConnection
if you wanted. 因此,如果需要,您也可以为SqlConnection
发出该消息。
SQLBulkCopy class might help. SQLBulkCopy类可能会有所帮助。
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx http://msdn.microsoft.com/zh-CN/library/system.data.sqlclient.sqlbulkcopy.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.