2010年9月14日 星期二

SqlBulkCopy 构造函数 (String, SqlBulkCopyOptions)

下面的控制台应用程序演示如何使用一个指定为字符串的连接执行批量加载。其中设置了一个选项以在加载目标表时使用源表的标识列中的值。在此示例中,首先将 SQL Server 表中的源数据读取到 SqlDataReader 实例。源表和目标表中各包括一个“标识”列。默认情况下,在目标表中会为每个添加的行生成一个新的“标识”列值。此示例设置一个选项以在打开强制执行批量加载进程的连接时使用源表的“标识”值。若要了解此选项如何改变批量加载的工作方式,请在 dbo.BulkCopyDemoMatchingColumns 表为空的情况下运行该示例。所有行均从源处加载。然后再次运行示例而不清空表。这将引发异常,并且代码会在控制台中写入一条消息,通知您由于主键违反约束尚未添加行。

Imports System.Data.SqlClient

Module Module1
Sub Main()
Dim connectionString As String = GetConnectionString()

' Open a connection to the AdventureWorks database.
Using sourceConnection As SqlConnection = _
New SqlConnection(connectionString)
sourceConnection.Open()

' Perform an initial count on the destination table.
Dim commandRowCount As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", _
sourceConnection)
Dim countStart As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", countStart)

' Get data from the source table as a SqlDataReader.
Dim commandSourceData As SqlCommand = New SqlCommand( _
"SELECT ProductID, Name, ProductNumber " & _
"FROM Production.Product;", sourceConnection)
Dim reader As SqlDataReader = commandSourceData.ExecuteReader

' Create the SqlBulkCopy object using a connection string
' and the KeepIdentity option.
' In the real world you would not use SqlBulkCopy to move
' data from one table to the other in the same database.
Using bulkCopy As SqlBulkCopy = _
New SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity)
bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"

Try
' Write from the source to the destination.
bulkCopy.WriteToServer(reader)

Catch ex As Exception
Console.WriteLine(ex.Message)

Finally
' Close the SqlDataReader. The SqlBulkCopy
' object is automatically closed at the end
' of the Using block.
reader.Close()
End Try
End Using

' Perform a final count on the destination table
' to see how many rows were added.
Dim countEnd As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Ending row count = {0}", countEnd)
Console.WriteLine("{0} rows were added.", countEnd - countStart)

Console.WriteLine("Press Enter to finish.")
Console.ReadLine()
End Using
End Sub

Private Function GetConnectionString() As String
' To avoid storing the sourceConnection string in your code,
' you can retrieve it from a configuration file.
Return "Data Source=(local);" & _
"Integrated Security=true;" & _
"Initial Catalog=AdventureWorks;"
End Function
End Module

沒有留言:

張貼留言