SqlBulkCopy เป็น class ที่ใช้ในการ Imports Data
โดยเป็นความสามารถอีกอย่างหนึ่งของ VS2005
private static void CopyDataToBulkCopyDemoMatchingColumns()
{
Console.WriteLine("Copying data to BulkCopyDemoMatchingColumns table...");
SqlConnection sourceConnection = new SqlConnection(GetConnectionString());
SqlConnection destConnection = new SqlConnection(GetConnectionString());
SqlDataReader reader = null;
try
{
// Open connections to the Adventure Works database, to read and write data.
sourceConnection.Open();
destConnection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;",
destConnection);
int countStart = (int)commandRowCount.ExecuteScalar();
Console.WriteLine("Starting row count = " + countStart);
// Get data from the source table as a SqlDataReader.
SqlCommand commandSourceData = new SqlCommand(
"SELECT ProductID, Name, ProductNumber, ListPrice FROM Production.Product;",
sourceConnection);
reader = commandSourceData.ExecuteReader();
// Set up the bulk copy object.
// The column positions in the source data reader match those
// in the destination table, so there is no need to map columns.
SqlBulkCopy bcp = new SqlBulkCopy(destConnection);
bcp.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns";
bcp.BatchSize = 20;
// Write from the source to the destination.
bcp.WriteToServer(reader);
bcp.Close();
// Find out how many rows were added to the destination table.
int countEnd = (int)commandRowCount.ExecuteScalar();
Console.WriteLine("Ending row count = " + countEnd);
Console.WriteLine(countEnd - countStart + " rows were added.");
}
catch (Exception ex)
{
Console.WriteLine("An exception occurred: {0}", ex.Message);
}
finally
{
if (sourceConnection != null)
sourceConnection.Close();
if (destConnection != null)
destConnection.Close();
if (reader != null)
reader.Close();
}
Console.WriteLine("-----------------------------------------------------");
}
ไม่มีความเห็น