SqlBulkCopy 建構函式
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
初始化 SqlBulkCopy 類別的新執行個體。
多載
| 名稱 | Description |
|---|---|
| SqlBulkCopy(SqlConnection) |
使用 SqlBulkCopy 的指定開放執行個體,以初始化 SqlConnection 類別的新執行個體。 |
| SqlBulkCopy(String) |
根據所提供的 SqlConnection 來初始化並開啟 |
| SqlBulkCopy(String, SqlBulkCopyOptions) |
根據所提供的 SqlConnection 來初始化並開啟 |
| SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction) |
使用提供的現有開放實例SqlBulkCopy初始化該SqlConnection類別的新實例。 該 SqlBulkCopy 實例依據參數中提供的 |
SqlBulkCopy(SqlConnection)
使用 SqlBulkCopy 的指定開放執行個體,以初始化 SqlConnection 類別的新執行個體。
public:
SqlBulkCopy(System::Data::SqlClient::SqlConnection ^ connection);
public SqlBulkCopy(System.Data.SqlClient.SqlConnection connection);
new System.Data.SqlClient.SqlBulkCopy : System.Data.SqlClient.SqlConnection -> System.Data.SqlClient.SqlBulkCopy
Public Sub New (connection As SqlConnection)
參數
- connection
- SqlConnection
已經開啟 SqlConnection 的實例,將用於執行批量複製操作。 如果你的連線字串沒有使用 Integrated Security = true,你可以用 SqlCredential 來比在連接字串中指定使用者 ID 和密碼更安全地傳遞使用者 ID 和密碼。
範例
以下主控台應用程式示範如何利用已開啟的連線批量載入資料。 在這個範例中,SqlDataReader 用於從 SQL Server AdventureWorks 資料庫的 Production.Product 資料表,將資料複製到同一資料庫中的類似資料表中。 此範例僅供示範用途。 你不會用 SqlBulkCopy 它來在同一資料庫中將資料從一個資料表移到另一個,在生產環境中。 請注意,來源資料不必位於 SQL Server;你可以使用任何可讀取或 IDataReader 載入到 DataTable的資料來源。
Important
除非您已如大量複製範例設定中所述建立工作資料表,否則將不會執行此範例。 這個程式碼僅是為了示範使用 SqlBulkCopy 的語法而提供。 如果來源和目的資料表在同一個 SQL Server 實例中,使用 Transact-SQL INSERT ... SELECT 語句來複製資料會更簡單且快速。
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
new SqlConnection(connectionString))
{
sourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoMatchingColumns;",
sourceConnection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
SqlCommand commandSourceData = new SqlCommand(
"SELECT ProductID, Name, " +
"ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader =
commandSourceData.ExecuteReader();
// Open the destination connection. In the real world you would
// not use SqlBulkCopy to move data from one table to the other
// in the same database. This is for demonstration purposes only.
using (SqlConnection destinationConnection =
new SqlConnection(connectionString))
{
destinationConnection.Open();
// Set up the bulk copy object.
// Note that the column positions in the source
// data reader match the column positions in
// the destination table so there is no need to
// map columns.
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(destinationConnection))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Close the SqlDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the using block.
reader.Close();
}
}
// Perform a final count on the destination
// table to see how many rows were added.
long countEnd = 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();
}
}
}
private static string GetConnectionString()
// 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;";
}
}
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 New SqlCommand( _
"SELECT ProductID, Name, ProductNumber " & _
"FROM Production.Product;", sourceConnection)
Dim reader As SqlDataReader = commandSourceData.ExecuteReader
' Open the destination connection. In the real world you would
' not use SqlBulkCopy to move data from one table to the other
' in the same database. This is for demonstration purposes only.
Using destinationConnection As SqlConnection = _
New SqlConnection(connectionString)
destinationConnection.Open()
' Set up the bulk copy object.
' The column positions in the source data reader
' match the column positions in the destination table,
' so there is no need to map columns.
Using bulkCopy As SqlBulkCopy = _
New SqlBulkCopy(destinationConnection)
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 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
備註
由於連線在實例初始化時 SqlBulkCopy 已經開啟,因此實例關閉後 SqlBulkCopy 連線仍保持開啟狀態。
若參數 connection 為空,則拋出 an ArgumentNullException 。
另請參閱
適用於
SqlBulkCopy(String)
根據所提供的 SqlConnection 來初始化並開啟 connectionString 的新執行個體。 這個建構函式會使用 SqlConnection 來初始化 SqlBulkCopy 類別的新執行個體。
public:
SqlBulkCopy(System::String ^ connectionString);
public SqlBulkCopy(string connectionString);
new System.Data.SqlClient.SqlBulkCopy : string -> System.Data.SqlClient.SqlBulkCopy
Public Sub New (connectionString As String)
參數
- connectionString
- String
定義將被實例開啟 SqlBulkCopy 的連線的字串。 如果你的連接字串不使用 Integrated Security = true,你可以使用 SqlBulkCopy(SqlConnection) 或 SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction) 和 SqlCredential,比起在連接字串中以文字形式指定使用者 ID 和密碼更安全地傳遞使用者 ID 和密碼。
範例
以下主控台應用程式示範如何利用指定為字串的連線來批量載入資料。 當實 SqlBulkCopy 例關閉時,連線會自動關閉。
在此範例中,來源資料首先從 SQL Server 資料表讀取到實 SqlDataReader 例。 來源資料不必位於 SQL Server;你可以使用任何可讀取或 IDataReader 載入到 DataTable的資料來源。
Important
除非您已如大量複製範例設定中所述建立工作資料表,否則將不會執行此範例。 這個程式碼僅是為了示範使用 SqlBulkCopy 的語法而提供。 如果來源和目的資料表在同一個 SQL Server 實例中,使用 Transact-SQL INSERT ... SELECT 語句來複製資料會更簡單且快速。
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
new SqlConnection(connectionString))
{
sourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoMatchingColumns;",
sourceConnection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
SqlCommand commandSourceData = new SqlCommand(
"SELECT ProductID, Name, " +
"ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader =
commandSourceData.ExecuteReader();
// Set up the bulk copy object using a connection string.
// In the real world you would not use SqlBulkCopy to move
// data from one table to the other in the same database.
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(connectionString))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Close the SqlDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the using block.
reader.Close();
}
}
// Perform a final count on the destination
// table to see how many rows were added.
long countEnd = 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();
}
}
private static string GetConnectionString()
// 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;";
}
}
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
' Set up the bulk copy object using a connection string.
' 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)
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
備註
在批量複製操作結束時,連線會自動關閉。
若connectionString為零,則拋出 。ArgumentNullException 若connectionString為空字串,則拋出 。ArgumentException
另請參閱
適用於
SqlBulkCopy(String, SqlBulkCopyOptions)
根據所提供的 SqlConnection 來初始化並開啟 connectionString 的新執行個體。 建構子會利用這個方法 SqlConnection 初始化該 SqlBulkCopy 類別的新實例。 該 SqlConnection 實例依據參數中提供的 copyOptions 選項行為。
public:
SqlBulkCopy(System::String ^ connectionString, System::Data::SqlClient::SqlBulkCopyOptions copyOptions);
public SqlBulkCopy(string connectionString, System.Data.SqlClient.SqlBulkCopyOptions copyOptions);
new System.Data.SqlClient.SqlBulkCopy : string * System.Data.SqlClient.SqlBulkCopyOptions -> System.Data.SqlClient.SqlBulkCopy
Public Sub New (connectionString As String, copyOptions As SqlBulkCopyOptions)
參數
- connectionString
- String
定義將被實例開啟 SqlBulkCopy 的連線的字串。 如果你的連接字串不使用 Integrated Security = true,你可以使用 SqlBulkCopy(SqlConnection) 或 SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction) 和 SqlCredential,比起在連接字串中以文字形式指定使用者 ID 和密碼更安全地傳遞使用者 ID 和密碼。
- copyOptions
- SqlBulkCopyOptions
列舉中的數值 SqlBulkCopyOptions 組合決定哪些資料來源列會被複製到目的資料表。
範例
以下主控台應用程式示範如何利用指定為字串的連線來執行批量載入。 在載入目的資料表時,會設定一個選項使用來源資料表的身份欄位中的值。 在此範例中,來源資料首先從 SQL Server 資料表讀取到實 SqlDataReader 例。 來源資料表與目的資料表各自包含一個身份欄位。 預設情況下,目標資料表中會為每新增一列產生一個新的 身份欄位值 。 在此範例中,當連線開啟時會設定一個選項,強制批量載入程序使用來源資料表中的 Identity 值。 想看看這個選項如何改變批量裝載的運作方式,可以用 DBO 跑取樣 。BulkCopyDemoMatchingColumns 表格為空。 所有列都是從來源載入。 然後再跑一次樣本,且不清空表格。 拋出一個例外,程式碼會寫訊息給主控台,通知你因為主鍵限制違規而沒有新增列數。
Important
除非您已如大量複製範例設定中所述建立工作資料表,否則將不會執行此範例。 這個程式碼僅是為了示範使用 SqlBulkCopy 的語法而提供。 如果來源和目的資料表在同一個 SQL Server 實例中,使用 Transact-SQL INSERT ... SELECT 語句來複製資料會更簡單且快速。
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a sourceConnection to the AdventureWorks database.
using (SqlConnection sourceConnection =
new SqlConnection(connectionString))
{
sourceConnection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoMatchingColumns;",
sourceConnection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Get data from the source table as a SqlDataReader.
SqlCommand commandSourceData = new SqlCommand(
"SELECT ProductID, Name, " +
"ProductNumber " +
"FROM Production.Product;", sourceConnection);
SqlDataReader reader =
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 (SqlBulkCopy bulkCopy =
new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(reader);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Close the SqlDataReader. The SqlBulkCopy
// object is automatically closed at the end
// of the using block.
reader.Close();
}
}
// Perform a final count on the destination
// table to see how many rows were added.
long countEnd = 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();
}
}
private static string GetConnectionString()
// 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;";
}
}
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
備註
你可以獲得本主題中所有批量影印選項 SqlBulkCopyOptions 的詳細資訊。
另請參閱
適用於
SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction)
使用提供的現有開放實例SqlBulkCopy初始化該SqlConnection類別的新實例。 該 SqlBulkCopy 實例依據參數中提供的 copyOptions 選項行為。 如果提供非空 SqlTransaction ,複製操作會在該交易內執行。
public:
SqlBulkCopy(System::Data::SqlClient::SqlConnection ^ connection, System::Data::SqlClient::SqlBulkCopyOptions copyOptions, System::Data::SqlClient::SqlTransaction ^ externalTransaction);
public SqlBulkCopy(System.Data.SqlClient.SqlConnection connection, System.Data.SqlClient.SqlBulkCopyOptions copyOptions, System.Data.SqlClient.SqlTransaction externalTransaction);
new System.Data.SqlClient.SqlBulkCopy : System.Data.SqlClient.SqlConnection * System.Data.SqlClient.SqlBulkCopyOptions * System.Data.SqlClient.SqlTransaction -> System.Data.SqlClient.SqlBulkCopy
Public Sub New (connection As SqlConnection, copyOptions As SqlBulkCopyOptions, externalTransaction As SqlTransaction)
參數
- connection
- SqlConnection
已經開啟 SqlConnection 的實例,將用於執行批量複製。 如果你的連線字串沒有使用 Integrated Security = true,你可以用 SqlCredential 來比在連接字串中指定使用者 ID 和密碼更安全地傳遞使用者 ID 和密碼。
- copyOptions
- SqlBulkCopyOptions
列舉中的數值 SqlBulkCopyOptions 組合決定哪些資料來源列會被複製到目的資料表。
- externalTransaction
- SqlTransaction
一個已存在 SqlTransaction 的實例,將在此下進行大量複製。
備註
若選項包含 UseInternalTransaction 且 externalTransaction 參數非空,則會拋出 InvalidArgumentException 。
關於如何在交易中使用 SqlBulkCopy 的範例,請參見 交易與批量複製操作。