SqlBulkCopy.WriteToServer 메서드
정의
중요
일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.
데이터 소스의 모든 행을 DestinationTableName 개체의 SqlBulkCopy 속성에 지정된 대상 테이블로 복사합니다.
오버로드
WriteToServer(DataTable, DataRowState) |
제공된 DataTable에서 제공된 행 상태와 일치하는 행만을 DestinationTableName 개체의 SqlBulkCopy 속성에 지정된 대상 테이블로 복사합니다. |
WriteToServer(IDataReader) |
제공된 IDataReader의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성으로 지정된 대상 테이블에 복사합니다. |
WriteToServer(DataTable) |
제공된 DataTable의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성으로 지정된 대상 테이블에 복사합니다. |
WriteToServer(DbDataReader) |
제공된 DbDataReader 배열의 모든 행을 DestinationTableName 개체의 SqlBulkCopy 속성에 지정된 대상 테이블로 복사합니다. |
WriteToServer(DataRow[]) |
제공된 DataRow 배열의 모든 행을 DestinationTableName 개체의 SqlBulkCopy 속성에 지정된 대상 테이블로 복사합니다. |
설명
MARS(여러 활성 결과 집합)를 사용하지 않도록 설정 WriteToServer 하면 연결이 사용 중입니다. MARS를 사용하는 경우 호출을 동일한 연결의 다른 명령과 인터리브할 WriteToServer 수 있습니다.
WriteToServer(DataTable, DataRowState)
제공된 DataTable에서 제공된 행 상태와 일치하는 행만을 DestinationTableName 개체의 SqlBulkCopy 속성에 지정된 대상 테이블로 복사합니다.
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)
매개 변수
- rowState
- DataRowState
DataRowState 열거형의 값입니다. 행 상태가 일치하는 행만 대상에 복사됩니다.
예제
다음 콘솔 애플리케이션에는 대량으로 하는 방법을 보여 줍니다.의 행만 로드는 DataTable 와 일치 하는 지정된 된 상태입니다. 이 경우 변경되지 않은 행만 추가됩니다. 대상 테이블은 AdventureWorks 데이터베이스의 테이블입니다.
이 예제에서는 런타임에 이 DataTable 만들어지고 세 개의 행이 추가됩니다. 메서드를 WriteToServer 실행하기 전에 행 중 하나가 편집됩니다. 메서드는 WriteToServer 인수를 사용하여 DataRowState.Unchanged
rowState
호출되므로 변경되지 않은 두 행만 대상에 대량 복사됩니다.
중요
이 샘플은 가져올 대량 복사 샘플 설정에 설명된 대로 작업 테이블을 만들지 않은 경우 실행되지 않습니다. 이 코드는 SqlBulkCopy를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 테이블과 대상 테이블이 동일한 SQL Server instance 있는 경우 Transact-SQL INSERT ... SELECT
문을 사용하여 데이터를 복사하는 것이 더 쉽고 빠릅니다.
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
설명
인수에 DataTable 표시되고 삭제되지 않은 상태에 있는 rowState
의 행만 대상 테이블에 복사됩니다.
대량 복사 작업이 진행되는 동안 연결된 대상 SqlConnection 은 처리 중이며 연결에서 다른 작업을 수행할 수 없습니다.
컬렉션은 ColumnMappings 열에서 DataTable 대상 데이터베이스 테이블로 매핑됩니다.
추가 정보
적용 대상
WriteToServer(IDataReader)
제공된 IDataReader의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성으로 지정된 대상 테이블에 복사합니다.
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)
매개 변수
- reader
- IDataReader
대상 테이블로 복사될 행이 포함된 IDataReader입니다.
예제
다음 콘솔 애플리케이션 데이터 대량 로드에서 하는 방법에 설명 된 SqlDataReader합니다. 대상 테이블은 AdventureWorks 데이터베이스의 테이블입니다.
중요
이 샘플은 가져올 대량 복사 샘플 설정에 설명된 대로 작업 테이블을 만들지 않은 경우 실행되지 않습니다. 이 코드는 SqlBulkCopy를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 테이블과 대상 테이블이 동일한 SQL Server instance 있는 경우 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
설명
복사 작업은 판독기에서 사용 가능한 다음 행에서 시작됩니다. 대부분의 경우 판독기가 방금 또는 유사한 호출에 의해 ExecuteReader 반환되었으므로 사용 가능한 다음 행이 첫 번째 행입니다. 여러 결과를 처리하려면 데이터 판독기에서 를 호출 NextResult 하고 다시 호출 WriteToServer 합니다.
를 사용하면 WriteToServer 판독기의 상태가 수정된다는 점에 유의하세요. 메서드는 false를 반환하거나 작업이 중단되거나 오류가 발생할 때까지 를 호출 Read 합니다. 즉, 작업이 완료되면 데이터 판독기가 결과 집합 WriteToServer 의 끝에 있는 다른 상태에 있을 수 있습니다.
대량 복사 작업이 진행되는 동안 연결된 대상 SqlConnection 은 처리 중이며 연결에서 다른 작업을 수행할 수 없습니다.
컬렉션은 ColumnMappings 데이터 판독기 열에서 대상 데이터베이스 테이블로 매핑됩니다.
추가 정보
적용 대상
WriteToServer(DataTable)
제공된 DataTable의 모든 행을 SqlBulkCopy 개체의 DestinationTableName 속성으로 지정된 대상 테이블에 복사합니다.
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)
매개 변수
예제
다음 콘솔 애플리케이션 데이터 대량 로드에서 하는 방법에 설명 된 DataTable합니다. 대상 테이블은 AdventureWorks 데이터베이스의 테이블입니다.
이 예제에서 는 DataTable 런타임에 만들어지고 는 작업의 원본 SqlBulkCopy
입니다.
중요
이 샘플은 가져올 대량 복사 샘플 설정에 설명된 대로 작업 테이블을 만들지 않은 경우 실행되지 않습니다. 이 코드는 SqlBulkCopy를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 테이블과 대상 테이블이 동일한 SQL Server instance 있는 경우 Transact-SQL INSERT ... SELECT
문을 사용하여 데이터를 복사하는 것이 더 쉽고 빠릅니다.
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
설명
의 모든 행 DataTable 은 삭제된 행을 제외하고 대상 테이블에 복사됩니다.
대량 복사 작업이 진행되는 동안 연결된 대상 SqlConnection 은 처리 중이며 연결에서 다른 작업을 수행할 수 없습니다.
컬렉션은 ColumnMappings 열에서 DataTable 대상 데이터베이스 테이블로 매핑됩니다.
추가 정보
적용 대상
WriteToServer(DbDataReader)
제공된 DbDataReader 배열의 모든 행을 DestinationTableName 개체의 SqlBulkCopy 속성에 지정된 대상 테이블로 복사합니다.
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)
매개 변수
- reader
- DbDataReader
대상 테이블로 복사될 행이 포함된 DbDataReader입니다.
적용 대상
WriteToServer(DataRow[])
제공된 DataRow 배열의 모든 행을 DestinationTableName 개체의 SqlBulkCopy 속성에 지정된 대상 테이블로 복사합니다.
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())
매개 변수
예제
다음 콘솔 애플리케이션 데이터 대량 로드에서 하는 방법에 설명 된 DataRow 배열입니다. 대상 테이블은 AdventureWorks 데이터베이스의 테이블입니다.
이 예제에서는 DataTable 런타임에 가 만들어집니다. 대상 테이블에 복사할 단일 행이 에서 DataTable 선택됩니다.
중요
이 샘플은 가져올 대량 복사 샘플 설정에 설명된 대로 작업 테이블을 만들지 않은 경우 실행되지 않습니다. 이 코드는 SqlBulkCopy를 사용하는 구문을 보여 주는 용도로 제공됩니다. 원본 테이블과 대상 테이블이 동일한 SQL Server instance 있는 경우 Transact-SQL INSERT ... SELECT
문을 사용하여 데이터를 복사하는 것이 더 쉽고 빠릅니다.
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
설명
대량 복사 작업이 진행되는 동안 연결된 대상 SqlConnection 은 처리 중이며 연결에서 다른 작업을 수행할 수 없습니다.
컬렉션은 ColumnMappings 열에서 DataRow 대상 데이터베이스 테이블로 매핑됩니다.
추가 정보
적용 대상
.NET
피드백
https://aka.ms/ContentUserFeedback
출시 예정: 2024년 내내 콘텐츠에 대한 피드백 메커니즘으로 GitHub 문제를 단계적으로 폐지하고 이를 새로운 피드백 시스템으로 바꿀 예정입니다. 자세한 내용은 다음을 참조하세요.다음에 대한 사용자 의견 제출 및 보기