SqlBulkCopy Constructeurs
Définition
Important
Certaines informations portent sur la préversion du produit qui est susceptible d’être en grande partie modifiée avant sa publication. Microsoft exclut toute garantie, expresse ou implicite, concernant les informations fournies ici.
Initialise une nouvelle instance de la classe SqlBulkCopy.
Surcharges
| Nom | Description |
|---|---|
| SqlBulkCopy(SqlConnection) |
Initialise une nouvelle instance de la classe SqlBulkCopy à l’aide de l’instance ouverte spécifiée de SqlConnection. |
| SqlBulkCopy(String) |
Initialise et ouvre une nouvelle instance de SqlConnection selon la |
| SqlBulkCopy(String, SqlBulkCopyOptions) |
Initialise et ouvre une nouvelle instance de SqlConnection selon la |
| SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction) |
Initialise une nouvelle instance de la SqlBulkCopy classe à l’aide de l’instance ouverte existante fournie de SqlConnection. L’instance SqlBulkCopy se comporte en fonction des options fournies dans le |
SqlBulkCopy(SqlConnection)
Initialise une nouvelle instance de la classe SqlBulkCopy à l’aide de l’instance ouverte spécifiée de 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)
Paramètres
- connection
- SqlConnection
Instance déjà ouverte SqlConnection qui sera utilisée pour effectuer l’opération de copie en bloc. Si votre chaîne de connexion n’utilise Integrated Security = truepas, vous pouvez utiliser SqlCredential pour transmettre l’ID d’utilisateur et le mot de passe de manière plus sécurisée que en spécifiant l’ID d’utilisateur et le mot de passe comme texte dans la chaîne de connexion.
Exemples
L’application console suivante montre comment charger en bloc des données à l’aide d’une connexion déjà ouverte. Dans cet exemple, SqlDataReader est utilisé pour copier des données de la table Production.Product dans la base de données AdventureWorks SQL Server vers une table semblable dans la même base de données. Cet exemple est uniquement à des fins de démonstration. Vous n’utilisez SqlBulkCopy pas pour déplacer des données d’une table vers une autre dans la même base de données dans une application de production. Notez que les données sources ne doivent pas être situées sur SQL Server ; vous pouvez utiliser n’importe quelle source de données qui peut être lue dans un IDataReader ou chargé dans un DataTable.
Important
Cet exemple ne s’exécute pas, sauf si vous avez créé les tables de travail comme décrit dans l’exemple de configuration de copie en bloc. Ce code est fourni uniquement pour illustrer la syntaxe de l’utilisation de SqlBulkCopy. Si les tables source et de destination se trouvent dans la même instance SQL Server, il est plus facile et plus rapide d’utiliser une instruction Transact-SQL INSERT ... SELECT pour copier les données.
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
Remarques
Étant donné que la connexion est déjà ouverte lorsque l’instance SqlBulkCopy est initialisée, la connexion reste ouverte une fois l’instance SqlBulkCopy fermée.
Si l’argument a la connection valeur Null, une ArgumentNullException valeur est levée.
Voir aussi
S’applique à
SqlBulkCopy(String)
Initialise et ouvre une nouvelle instance de SqlConnection selon la connectionString fournie. Le constructeur utilise la SqlConnection pour initialiser une nouvelle instance de la classe 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)
Paramètres
- connectionString
- String
Chaîne définissant la connexion qui sera ouverte pour une utilisation par l’instance SqlBulkCopy . Si votre chaîne de connexion n’utilise pas Integrated Security = true, vous pouvez utiliser SqlBulkCopy(SqlConnection) ou SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction) et SqlCredential pour transmettre l’ID d’utilisateur et le mot de passe de manière plus sécurisée que en spécifiant l’ID d’utilisateur et le mot de passe comme texte dans le chaîne de connexion.
Exemples
L’application console suivante montre comment charger en bloc des données à l’aide d’une connexion spécifiée sous forme de chaîne. La connexion est automatiquement fermée lorsque l’instance SqlBulkCopy est fermée.
Dans cet exemple, les données sources sont d’abord lues à partir d’une table SQL Server vers une SqlDataReader instance. Les données sources ne doivent pas être situées sur SQL Server ; vous pouvez utiliser n’importe quelle source de données qui peut être lue dans un IDataReader ou chargé dans un DataTable.
Important
Cet exemple ne s’exécute pas, sauf si vous avez créé les tables de travail comme décrit dans l’exemple de configuration de copie en bloc. Ce code est fourni uniquement pour illustrer la syntaxe de l’utilisation de SqlBulkCopy. Si les tables source et de destination se trouvent dans la même instance SQL Server, il est plus facile et plus rapide d’utiliser une instruction Transact-SQL INSERT ... SELECT pour copier les données.
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
Remarques
La connexion est automatiquement fermée à la fin de l’opération de copie en bloc.
Si connectionString la valeur est Null, une ArgumentNullException valeur est levée. S’il connectionString s’agit d’une chaîne vide, une ArgumentException chaîne est levée.
Voir aussi
S’applique à
SqlBulkCopy(String, SqlBulkCopyOptions)
Initialise et ouvre une nouvelle instance de SqlConnection selon la connectionString fournie. Le constructeur l’utilise SqlConnection pour initialiser une nouvelle instance de la SqlBulkCopy classe. L’instance SqlConnection se comporte en fonction des options fournies dans le copyOptions paramètre.
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)
Paramètres
- connectionString
- String
Chaîne définissant la connexion qui sera ouverte pour une utilisation par l’instance SqlBulkCopy . Si votre chaîne de connexion n’utilise pas Integrated Security = true, vous pouvez utiliser SqlBulkCopy(SqlConnection) ou SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction) et SqlCredential pour transmettre l’ID d’utilisateur et le mot de passe de manière plus sécurisée que en spécifiant l’ID d’utilisateur et le mot de passe comme texte dans le chaîne de connexion.
- copyOptions
- SqlBulkCopyOptions
Combinaison de valeurs de l’énumération SqlBulkCopyOptions qui détermine les lignes de source de données copiées dans la table de destination.
Exemples
L’application console suivante montre comment effectuer une charge en bloc à l’aide d’une connexion spécifiée sous forme de chaîne. Une option est définie pour utiliser la valeur dans la colonne d’identité de la table source lorsque vous chargez la table de destination. Dans cet exemple, les données sources sont d’abord lues à partir d’une table SQL Server vers une SqlDataReader instance. La table source et la table de destination incluent chacune une colonne Identity. Par défaut, une nouvelle valeur pour la colonne Identity est générée dans la table de destination pour chaque ligne ajoutée. Dans cet exemple, une option est définie lorsque la connexion est ouverte, ce qui force le processus de chargement en bloc à utiliser les valeurs Identity de la table source à la place. Pour voir comment l’option modifie le fonctionnement du chargement en bloc, exécutez l’exemple avec le dbo. Table BulkCopyDemoMatchingColumns vide. Toutes les lignes sont chargées à partir de la source. Ensuite, réexécutez l’exemple sans vider la table. Une exception est levée et le code écrit un message dans la console vous informant que les lignes n’ont pas été ajoutées en raison de violations de contrainte de clé primaire.
Important
Cet exemple ne s’exécute pas, sauf si vous avez créé les tables de travail comme décrit dans l’exemple de configuration de copie en bloc. Ce code est fourni uniquement pour illustrer la syntaxe de l’utilisation de SqlBulkCopy. Si les tables source et de destination se trouvent dans la même instance SQL Server, il est plus facile et plus rapide d’utiliser une instruction Transact-SQL INSERT ... SELECT pour copier les données.
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
Remarques
Vous pouvez obtenir des informations détaillées sur toutes les options de copie en bloc dans la SqlBulkCopyOptions rubrique.
Voir aussi
S’applique à
SqlBulkCopy(SqlConnection, SqlBulkCopyOptions, SqlTransaction)
Initialise une nouvelle instance de la SqlBulkCopy classe à l’aide de l’instance ouverte existante fournie de SqlConnection. L’instance SqlBulkCopy se comporte en fonction des options fournies dans le copyOptions paramètre. Si une valeur non null SqlTransaction est fournie, les opérations de copie sont effectuées dans cette transaction.
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)
Paramètres
- connection
- SqlConnection
Instance déjà ouverte SqlConnection qui sera utilisée pour effectuer la copie en bloc. Si votre chaîne de connexion n’utilise Integrated Security = truepas, vous pouvez utiliser SqlCredential pour transmettre l’ID d’utilisateur et le mot de passe de manière plus sécurisée que en spécifiant l’ID d’utilisateur et le mot de passe comme texte dans la chaîne de connexion.
- copyOptions
- SqlBulkCopyOptions
Combinaison de valeurs de l’énumération SqlBulkCopyOptions qui détermine les lignes de source de données copiées dans la table de destination.
- externalTransaction
- SqlTransaction
Instance existante SqlTransaction sous laquelle la copie en bloc se produit.
Remarques
Si les options incluent UseInternalTransaction et que l’argument externalTransaction n’est pas null, une exception InvalidArgumentException est levée.
Pour obtenir des exemples illustrant comment utiliser SqlBulkCopy dans une transaction, consultez Opérations de transaction et de copie en bloc.