SqlBulkCopy.WriteToServer Yöntem
Tanım
Önemli
Bazı bilgiler ürünün ön sürümüyle ilgilidir ve sürüm öncesinde önemli değişiklikler yapılmış olabilir. Burada verilen bilgilerle ilgili olarak Microsoft açık veya zımni hiçbir garanti vermez.
Veri kaynağındaki tüm satırları nesnenin DestinationTableName özelliği tarafından belirtilen hedef tabloya SqlBulkCopy kopyalar.
Aşırı Yüklemeler
| Name | Description |
|---|---|
| WriteToServer(DataTable, DataRowState) |
Yalnızca sağlanan DataTable içindeki sağlanan satır durumuyla eşleşen satırları nesnenin özelliği tarafından DestinationTableName belirtilen hedef tabloya SqlBulkCopy kopyalar. |
| WriteToServer(IDataReader) |
Sağlanan IDataReader içindeki tüm satırları nesnenin DestinationTableName özelliği tarafından belirtilen bir hedef tabloya SqlBulkCopy kopyalar. |
| WriteToServer(DataTable) |
Sağlanan DataTable içindeki tüm satırları nesnenin DestinationTableName özelliği tarafından belirtilen bir hedef tabloya SqlBulkCopy kopyalar. |
| WriteToServer(DbDataReader) |
Sağlanan DbDataReader dizideki tüm satırları nesnenin DestinationTableName özelliği tarafından belirtilen hedef tabloya SqlBulkCopy kopyalar. |
| WriteToServer(DataRow[]) |
Sağlanan DataRow dizideki tüm satırları nesnenin DestinationTableName özelliği tarafından belirtilen hedef tabloya SqlBulkCopy kopyalar. |
Açıklamalar
Birden çok etkin sonuç kümesi (MARS) devre dışı bırakılırsa, WriteToServer bağlantı meşgul olur. MARS etkinse, çağrıları WriteToServer aynı bağlantıdaki diğer komutlarla birbirine ayırabilirsiniz.
WriteToServer(DataTable, DataRowState)
Yalnızca sağlanan DataTable içindeki sağlanan satır durumuyla eşleşen satırları nesnenin özelliği tarafından DestinationTableName belirtilen hedef tabloya SqlBulkCopy kopyalar.
public:
void WriteToServer(System::Data::DataTable ^ table, System::Data::DataRowState rowState);
public void WriteToServer(System.Data.DataTable table, System.Data.DataRowState rowState);
member this.WriteToServer : System.Data.DataTable * System.Data.DataRowState -> unit
Public Sub WriteToServer (table As DataTable, rowState As DataRowState)
Parametreler
- rowState
- DataRowState
Numaralandırmadan bir DataRowState değer. Yalnızca satır durumuyla eşleşen satırlar hedefe kopyalanır.
Örnekler
Aşağıdaki Konsol uygulaması, yalnızca belirtilen durumla eşleşen bir DataTable içindeki satırların nasıl toplu yüklendiğini gösterir. Bu durumda, yalnızca değişmemiş satırlar eklenir. Hedef tablo AdventureWorks veritabanındaki bir tablodur.
Bu örnekte, çalışma zamanında bir DataTable oluşturulur ve buna üç satır eklenir.
WriteToServer yöntemi yürütülmeden önce satırlardan biri düzenlenir.
WriteToServer yöntemi bir DataRowState.UnchangedrowState bağımsız değişkenle çağrılır, bu nedenle yalnızca iki değişmemiş satır hedefe toplu olarak kopyalanır.
Important
Bu örnek, Toplu Kopyalama Örneği Kurulumubölümünde açıklandığı gibi çalışma tablolarını oluşturmadığınız sürece çalışmaz. Bu kod, yalnızca SqlBulkCopy'yi kullanmaya yönelik söz dizimini göstermek için sağlanır. Kaynak ve hedef tablolar aynı SQL Server örneğindeyse, verileri kopyalamak için Transact-SQL INSERT ... SELECT deyimi kullanmak daha kolay ve daha hızlıdır.
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a connection to the AdventureWorks database.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoMatchingColumns;",
connection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Create a table with some rows.
DataTable newProducts = MakeTable();
// Make a change to one of the rows in the DataTable.
DataRow row = newProducts.Rows[0];
row.BeginEdit();
row["Name"] = "AAA";
row.EndEdit();
// Create the SqlBulkCopy object.
// Note that the column positions in the source DataTable
// match the column positions in the destination table so
// there is no need to map columns.
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
try
{
// Write unchanged rows from the source to the destination.
bulkCopy.WriteToServer(newProducts, DataRowState.Unchanged);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
// 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 DataTable MakeTable()
// Create a new DataTable named NewProducts.
{
DataTable newProducts = new DataTable("NewProducts");
// Add three column objects to the table.
DataColumn productID = new DataColumn();
productID.DataType = System.Type.GetType("System.Int32");
productID.ColumnName = "ProductID";
productID.AutoIncrement = true;
newProducts.Columns.Add(productID);
DataColumn productName = new DataColumn();
productName.DataType = System.Type.GetType("System.String");
productName.ColumnName = "Name";
newProducts.Columns.Add(productName);
DataColumn productNumber = new DataColumn();
productNumber.DataType = System.Type.GetType("System.String");
productNumber.ColumnName = "ProductNumber";
newProducts.Columns.Add(productNumber);
// Create an array for DataColumn objects.
DataColumn[] keys = new DataColumn[1];
keys[0] = productID;
newProducts.PrimaryKey = keys;
// Add some new rows to the collection.
DataRow row = newProducts.NewRow();
row["Name"] = "CC-101-WH";
row["ProductNumber"] = "Cyclocomputer - White";
newProducts.Rows.Add(row);
row = newProducts.NewRow();
row["Name"] = "CC-101-BK";
row["ProductNumber"] = "Cyclocomputer - Black";
newProducts.Rows.Add(row);
row = newProducts.NewRow();
row["Name"] = "CC-101-ST";
row["ProductNumber"] = "Cyclocomputer - Stainless";
newProducts.Rows.Add(row);
newProducts.AcceptChanges();
// Return the new DataTable.
return newProducts;
}
private static string GetConnectionString()
// To avoid storing the connection 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 connection As SqlConnection = _
New SqlConnection(connectionString)
connection.Open()
' Perform an initial count on the destination table.
Dim commandRowCount As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", _
connection)
Dim countStart As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", countStart)
' Create a table with some rows.
Dim newProducts As DataTable = MakeTable()
' Make a change to one of the rows in the DataTable.
Dim row As DataRow = newProducts.Rows(0)
row.BeginEdit()
row("Name") = "AAA"
row.EndEdit()
' Set up the bulk copy object.
' Note that the column positions in the source DataTable
' match the column positions in the destination table,
' so there is no need to map columns.
Using bulkCopy As SqlBulkCopy = _
New SqlBulkCopy(connection)
bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"
Try
' Write unchanged rows from the source to the destination.
bulkCopy.WriteToServer(newProducts, DataRowState.Unchanged)
Catch ex As Exception
Console.WriteLine(ex.Message)
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 MakeTable() As DataTable
' Create a new DataTable named NewProducts.
Dim newProducts As DataTable = _
New DataTable("NewProducts")
' Add three column objects to the table.
Dim productID As DataColumn = New DataColumn()
productID.DataType = System.Type.GetType("System.Int32")
productID.ColumnName = "ProductID"
productID.AutoIncrement = True
newProducts.Columns.Add(productID)
Dim productName As DataColumn = New DataColumn()
productName.DataType = System.Type.GetType("System.String")
productName.ColumnName = "Name"
newProducts.Columns.Add(productName)
Dim productNumber As DataColumn = New DataColumn()
productNumber.DataType = System.Type.GetType("System.String")
productNumber.ColumnName = "ProductNumber"
newProducts.Columns.Add(productNumber)
' Create an array for DataColumn objects.
Dim keys(0) As DataColumn
keys(0) = productID
newProducts.PrimaryKey = keys
' Add some new rows to the collection.
Dim row As DataRow
row = newProducts.NewRow()
row("Name") = "CC-101-WH"
row("ProductNumber") = "Cyclocomputer - White"
newProducts.Rows.Add(row)
row = newProducts.NewRow()
row("Name") = "CC-101-BK"
row("ProductNumber") = "Cyclocomputer - Black"
newProducts.Rows.Add(row)
row = newProducts.NewRow()
row("Name") = "CC-101-ST"
row("ProductNumber") = "Cyclocomputer - Stainless"
newProducts.Rows.Add(row)
newProducts.AcceptChanges()
' Return the new DataTable.
Return newProducts
End Function
Private Function GetConnectionString() As String
' To avoid storing the connection 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
Açıklamalar
Yalnızca bağımsız değişkende DataTable belirtilen ve silinmemiş durumdaki rowState satırlar hedef tabloya kopyalanır.
Note
Belirtilirse Deleted , herhangi bir Unchanged, Addedve Modified satırı da sunucuya kopyalanır. Özel durum oluşturulmayacak.
Toplu kopyalama işlemi devam ederken, ilişkili hedef SqlConnection bunu gerçekleştirmekle meşgul ve bağlantıda başka işlem gerçekleştirilemez.
Koleksiyon, ColumnMappings sütunlardan DataTable hedef veritabanı tablosuna eşler.
Ayrıca bkz.
Şunlara uygulanır
WriteToServer(IDataReader)
Sağlanan IDataReader içindeki tüm satırları nesnenin DestinationTableName özelliği tarafından belirtilen bir hedef tabloya SqlBulkCopy kopyalar.
public:
void WriteToServer(System::Data::IDataReader ^ reader);
public void WriteToServer(System.Data.IDataReader reader);
member this.WriteToServer : System.Data.IDataReader -> unit
Public Sub WriteToServer (reader As IDataReader)
Parametreler
- reader
- IDataReader
IDataReader Satırları hedef tabloya kopyalanacak olan.
Örnekler
Aşağıdaki konsol uygulaması, bir SqlDataReader'den toplu veri yükleme işlemini gösterir. Hedef tablo AdventureWorks veritabanındaki bir tablodur.
Important
Bu örnek, Toplu Kopyalama Örneği Kurulumubölümünde açıklandığı gibi çalışma tablolarını oluşturmadığınız sürece çalışmaz. Bu kod, yalnızca SqlBulkCopy'yi kullanmaya yönelik söz dizimini göstermek için sağlanır. Kaynak ve hedef tablolar aynı SQL Server örneğindeyse, verileri kopyalamak için Transact-SQL INSERT ... SELECT deyimi kullanmak daha kolay ve daha hızlıdır.
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
Açıklamalar
Kopyalama işlemi okuyucuda bir sonraki kullanılabilir satırda başlar. Çoğu zaman okuyucu tarafından veya benzer bir çağrı tarafından ExecuteReader döndürülür, bu nedenle sonraki kullanılabilir satır ilk satırdır. Birden çok sonucu işlemek için veri okuyucuyu arayın NextResult ve yeniden arayın WriteToServer .
kullanmanın WriteToServer okuyucunun durumunu değiştirdiğini unutmayın. yöntemi false döndürene, işlem durdurulana veya bir hata oluşana kadar çağırır Read . Bu, işlem tamamlandığında veri okuyucunun büyük olasılıkla sonuç kümesinin WriteToServer sonunda farklı bir durumda olacağı anlamına gelir.
Toplu kopyalama işlemi devam ederken, ilişkili hedef SqlConnection bunu gerçekleştirmekle meşgul ve bağlantıda başka işlem gerçekleştirilemez.
Koleksiyon, ColumnMappings veri okuyucu sütunlarından hedef veritabanı tablosuna eşler.
Ayrıca bkz.
Şunlara uygulanır
WriteToServer(DataTable)
Sağlanan DataTable içindeki tüm satırları nesnenin DestinationTableName özelliği tarafından belirtilen bir hedef tabloya SqlBulkCopy kopyalar.
public:
void WriteToServer(System::Data::DataTable ^ table);
public void WriteToServer(System.Data.DataTable table);
member this.WriteToServer : System.Data.DataTable -> unit
Public Sub WriteToServer (table As DataTable)
Parametreler
Örnekler
Aşağıdaki Konsol uygulaması, bir DataTable'den toplu veri yükleme işlemini gösterir. Hedef tablo AdventureWorks veritabanındaki bir tablodur.
Bu örnekte, çalışma zamanında bir DataTable oluşturulur ve işlemin kaynağıdır SqlBulkCopy .
Important
Bu örnek, Toplu Kopyalama Örneği Kurulumubölümünde açıklandığı gibi çalışma tablolarını oluşturmadığınız sürece çalışmaz. Bu kod, yalnızca SqlBulkCopy'yi kullanmaya yönelik söz dizimini göstermek için sağlanır. Kaynak ve hedef tablolar aynı SQL Server örneğindeyse, verileri kopyalamak için Transact-SQL INSERT ... SELECT deyimi kullanmak daha kolay ve daha hızlıdır.
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a connection to the AdventureWorks database.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoMatchingColumns;",
connection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Create a table with some rows.
DataTable newProducts = MakeTable();
// Create the SqlBulkCopy object.
// Note that the column positions in the source DataTable
// match the column positions in the destination table so
// there is no need to map columns.
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(newProducts);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
// 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 DataTable MakeTable()
// Create a new DataTable named NewProducts.
{
DataTable newProducts = new DataTable("NewProducts");
// Add three column objects to the table.
DataColumn productID = new DataColumn();
productID.DataType = System.Type.GetType("System.Int32");
productID.ColumnName = "ProductID";
productID.AutoIncrement = true;
newProducts.Columns.Add(productID);
DataColumn productName = new DataColumn();
productName.DataType = System.Type.GetType("System.String");
productName.ColumnName = "Name";
newProducts.Columns.Add(productName);
DataColumn productNumber = new DataColumn();
productNumber.DataType = System.Type.GetType("System.String");
productNumber.ColumnName = "ProductNumber";
newProducts.Columns.Add(productNumber);
// Create an array for DataColumn objects.
DataColumn[] keys = new DataColumn[1];
keys[0] = productID;
newProducts.PrimaryKey = keys;
// Add some new rows to the collection.
DataRow row = newProducts.NewRow();
row["Name"] = "CC-101-WH";
row["ProductNumber"] = "Cyclocomputer - White";
newProducts.Rows.Add(row);
row = newProducts.NewRow();
row["Name"] = "CC-101-BK";
row["ProductNumber"] = "Cyclocomputer - Black";
newProducts.Rows.Add(row);
row = newProducts.NewRow();
row["Name"] = "CC-101-ST";
row["ProductNumber"] = "Cyclocomputer - Stainless";
newProducts.Rows.Add(row);
newProducts.AcceptChanges();
// Return the new DataTable.
return newProducts;
}
private static string GetConnectionString()
// To avoid storing the connection 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 connection As SqlConnection = _
New SqlConnection(connectionString)
connection.Open()
' Perform an initial count on the destination table.
Dim commandRowCount As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", _
connection)
Dim countStart As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", countStart)
' Create a table with some rows.
Dim newProducts As DataTable = MakeTable()
' Note that the column positions in the source DataTable
' match the column positions in the destination table,
' so there is no need to map columns.
Using bulkCopy As SqlBulkCopy = _
New SqlBulkCopy(connection)
bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"
Try
' Write from the source to the destination.
bulkCopy.WriteToServer(newProducts)
Catch ex As Exception
Console.WriteLine(ex.Message)
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 MakeTable() As DataTable
' Create a new DataTable named NewProducts.
Dim newProducts As DataTable = _
New DataTable("NewProducts")
' Add three column objects to the table.
Dim productID As DataColumn = New DataColumn()
productID.DataType = System.Type.GetType("System.Int32")
productID.ColumnName = "ProductID"
productID.AutoIncrement = True
newProducts.Columns.Add(productID)
Dim productName As DataColumn = New DataColumn()
productName.DataType = System.Type.GetType("System.String")
productName.ColumnName = "Name"
newProducts.Columns.Add(productName)
Dim productNumber As DataColumn = New DataColumn()
productNumber.DataType = System.Type.GetType("System.String")
productNumber.ColumnName = "ProductNumber"
newProducts.Columns.Add(productNumber)
' Create an array for DataColumn objects.
Dim keys(0) As DataColumn
keys(0) = productID
newProducts.PrimaryKey = keys
' Add some new rows to the collection.
Dim row As DataRow
row = newProducts.NewRow()
row("Name") = "CC-101-WH"
row("ProductNumber") = "Cyclocomputer - White"
newProducts.Rows.Add(row)
row = newProducts.NewRow()
row("Name") = "CC-101-BK"
row("ProductNumber") = "Cyclocomputer - Black"
newProducts.Rows.Add(row)
row = newProducts.NewRow()
row("Name") = "CC-101-ST"
row("ProductNumber") = "Cyclocomputer - Stainless"
newProducts.Rows.Add(row)
newProducts.AcceptChanges()
' Return the new DataTable.
Return newProducts
End Function
Private Function GetConnectionString() As String
' To avoid storing the connection 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
Açıklamalar
içindeki DataTable tüm satırlar, silinmiş olanlar dışında hedef tabloya kopyalanır.
Toplu kopyalama işlemi devam ederken, ilişkili hedef SqlConnection bunu gerçekleştirmekle meşgul ve bağlantıda başka işlem gerçekleştirilemez.
Koleksiyon, ColumnMappings sütunlardan DataTable hedef veritabanı tablosuna eşler.
Ayrıca bkz.
Şunlara uygulanır
WriteToServer(DbDataReader)
Sağlanan DbDataReader dizideki tüm satırları nesnenin DestinationTableName özelliği tarafından belirtilen hedef tabloya SqlBulkCopy kopyalar.
public:
void WriteToServer(System::Data::Common::DbDataReader ^ reader);
public void WriteToServer(System.Data.Common.DbDataReader reader);
member this.WriteToServer : System.Data.Common.DbDataReader -> unit
Public Sub WriteToServer (reader As DbDataReader)
Parametreler
- reader
- DbDataReader
DbDataReader Satırları hedef tabloya kopyalanacak olan.
Şunlara uygulanır
WriteToServer(DataRow[])
Sağlanan DataRow dizideki tüm satırları nesnenin DestinationTableName özelliği tarafından belirtilen hedef tabloya SqlBulkCopy kopyalar.
public:
void WriteToServer(cli::array <System::Data::DataRow ^> ^ rows);
public void WriteToServer(System.Data.DataRow[] rows);
member this.WriteToServer : System.Data.DataRow[] -> unit
Public Sub WriteToServer (rows As DataRow())
Parametreler
Örnekler
Aşağıdaki konsol uygulaması, bir DataRow diziden toplu veri yükleme işlemini gösterir. Hedef tablo AdventureWorks veritabanındaki bir tablodur.
Bu örnekte, çalışma zamanında bir DataTable oluşturulur. Hedef tabloya kopyalamak için öğesinden DataTable tek bir satır seçilir.
Important
Bu örnek, Toplu Kopyalama Örneği Kurulumubölümünde açıklandığı gibi çalışma tablolarını oluşturmadığınız sürece çalışmaz. Bu kod, yalnızca SqlBulkCopy'yi kullanmaya yönelik söz dizimini göstermek için sağlanır. Kaynak ve hedef tablolar aynı SQL Server örneğindeyse, verileri kopyalamak için Transact-SQL INSERT ... SELECT deyimi kullanmak daha kolay ve daha hızlıdır.
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
// Open a connection to the AdventureWorks database.
using (SqlConnection connection =
new SqlConnection(connectionString))
{
connection.Open();
// Perform an initial count on the destination table.
SqlCommand commandRowCount = new SqlCommand(
"SELECT COUNT(*) FROM " +
"dbo.BulkCopyDemoMatchingColumns;",
connection);
long countStart = System.Convert.ToInt32(
commandRowCount.ExecuteScalar());
Console.WriteLine("Starting row count = {0}", countStart);
// Create a table with some rows.
DataTable newProducts = MakeTable();
// Get a reference to a single row in the table.
DataRow[] rowArray = newProducts.Select(
"Name='CC-101-BK'");
// Create the SqlBulkCopy object.
// Note that the column positions in the source DataTable
// match the column positions in the destination table so
// there is no need to map columns.
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName =
"dbo.BulkCopyDemoMatchingColumns";
try
{
// Write the array of rows to the destination.
bulkCopy.WriteToServer(rowArray);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
// 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 DataTable MakeTable()
// Create a new DataTable named NewProducts.
{
DataTable newProducts = new DataTable("NewProducts");
// Add three column objects to the table.
DataColumn productID = new DataColumn();
productID.DataType = System.Type.GetType("System.Int32");
productID.ColumnName = "ProductID";
productID.AutoIncrement = true;
newProducts.Columns.Add(productID);
DataColumn productName = new DataColumn();
productName.DataType = System.Type.GetType("System.String");
productName.ColumnName = "Name";
newProducts.Columns.Add(productName);
DataColumn productNumber = new DataColumn();
productNumber.DataType = System.Type.GetType("System.String");
productNumber.ColumnName = "ProductNumber";
newProducts.Columns.Add(productNumber);
// Create an array for DataColumn objects.
DataColumn[] keys = new DataColumn[1];
keys[0] = productID;
newProducts.PrimaryKey = keys;
// Add some new rows to the collection.
DataRow row = newProducts.NewRow();
row["Name"] = "CC-101-WH";
row["ProductNumber"] = "Cyclocomputer - White";
newProducts.Rows.Add(row);
row = newProducts.NewRow();
row["Name"] = "CC-101-BK";
row["ProductNumber"] = "Cyclocomputer - Black";
newProducts.Rows.Add(row);
row = newProducts.NewRow();
row["Name"] = "CC-101-ST";
row["ProductNumber"] = "Cyclocomputer - Stainless";
newProducts.Rows.Add(row);
newProducts.AcceptChanges();
// Return the new DataTable.
return newProducts;
}
private static string GetConnectionString()
// To avoid storing the connection 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 connection As SqlConnection = _
New SqlConnection(connectionString)
connection.Open()
' Perform an initial count on the destination table.
Dim commandRowCount As New SqlCommand( _
"SELECT COUNT(*) FROM dbo.BulkCopyDemoMatchingColumns;", _
connection)
Dim countStart As Long = _
System.Convert.ToInt32(commandRowCount.ExecuteScalar())
Console.WriteLine("Starting row count = {0}", countStart)
' Create a table with some rows.
Dim newProducts As DataTable = MakeTable()
' Get a reference to a single row in the table.
Dim rowArray() As DataRow = newProducts.Select( _
"Name='CC-101-BK'")
' Note that the column positions in the source DataTable
' match the column positions in the destination table,
' so there is no need to map columns.
Using bulkCopy As SqlBulkCopy = _
New SqlBulkCopy(connection)
bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns"
Try
' Write the array of rows to the destination.
bulkCopy.WriteToServer(rowArray)
Catch ex As Exception
Console.WriteLine(ex.Message)
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 MakeTable() As DataTable
' Create a new DataTable named NewProducts.
Dim newProducts As DataTable = _
New DataTable("NewProducts")
' Add three column objects to the table.
Dim productID As DataColumn = New DataColumn()
productID.DataType = System.Type.GetType("System.Int32")
productID.ColumnName = "ProductID"
productID.AutoIncrement = True
newProducts.Columns.Add(productID)
Dim productName As DataColumn = New DataColumn()
productName.DataType = System.Type.GetType("System.String")
productName.ColumnName = "Name"
newProducts.Columns.Add(productName)
Dim productNumber As DataColumn = New DataColumn()
productNumber.DataType = System.Type.GetType("System.String")
productNumber.ColumnName = "ProductNumber"
newProducts.Columns.Add(productNumber)
' Create an array for DataColumn objects.
Dim keys(0) As DataColumn
keys(0) = productID
newProducts.PrimaryKey = keys
' Add some new rows to the collection.
Dim row As DataRow
row = newProducts.NewRow()
row("Name") = "CC-101-WH"
row("ProductNumber") = "Cyclocomputer - White"
newProducts.Rows.Add(row)
row = newProducts.NewRow()
row("Name") = "CC-101-BK"
row("ProductNumber") = "Cyclocomputer - Black"
newProducts.Rows.Add(row)
row = newProducts.NewRow()
row("Name") = "CC-101-ST"
row("ProductNumber") = "Cyclocomputer - Stainless"
newProducts.Rows.Add(row)
newProducts.AcceptChanges()
' Return the new DataTable.
Return newProducts
End Function
Private Function GetConnectionString() As String
' To avoid storing the connection 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
Açıklamalar
Toplu kopyalama işlemi devam ederken, ilişkili hedef SqlConnection bunu gerçekleştirmekle meşgul ve bağlantıda başka işlem gerçekleştirilemez.
Koleksiyon, ColumnMappings sütunlardan DataRow hedef veritabanı tablosuna eşler.