Share via


Tekil Toplu Kopyalama İşlemleri

SQL Server toplu kopyalama işlemi gerçekleştirmenin en basit yaklaşımı, veritabanında tek bir işlem gerçekleştirmektir. Varsayılan olarak, toplu kopyalama işlemi yalıtılmış bir işlem olarak gerçekleştirilir: Kopyalama işlemi işlem yapılmamış bir şekilde gerçekleşir ve geri döndürme fırsatı yoktur.

Not

Hata oluştuğunda toplu kopyanın tamamını veya bir bölümünü geri almanız gerekiyorsa, yönetilen bir işlem kullanabilir veya mevcut bir SqlBulkCopyişlem içinde toplu kopyalama işlemini gerçekleştirebilirsiniz. Bağlantı bir System.Transactions işlemine (örtük veya açıkça) dahil edilirse SqlBulkCopy ile de çalışırSystem.Transactions.

Daha fazla bilgi için bkz . İşlem ve Toplu Kopyalama İşlemleri.

Toplu kopyalama işlemi gerçekleştirmeye yönelik genel adımlar şunlardır:

  1. Kaynak sunucuya Bağlan ve kopyalanacak verileri alın. Veriler bir veya DataTable nesnesinden alınabiliyorsa diğer kaynaklardan IDataReader da gelebilir.

  2. Hedef sunucuya Bağlan (SqlBulkCopy'nin sizin için bir bağlantı kurmasını istemiyorsanız).

  3. Gerekli özellikleri ayarlayarak bir SqlBulkCopy nesne oluşturun.

  4. DestinationTableName özelliğini, toplu ekleme işleminin hedef tablosunu gösterecek şekilde ayarlayın.

  5. WriteToServer yöntemlerinden birini çağırın.

  6. İsteğe bağlı olarak, özellikleri güncelleştirin ve gerektiğinde WriteToServer'ı yeniden çağırarak.

  7. çağrısı gerçekleştirin Closeveya toplu kopyalama işlemlerini bir Using deyim içinde sarmalayın.

Dikkat

Kaynak ve hedef sütun veri türlerinin eşleşmesini öneririz. Veri türleri eşleşmiyorsa, SqlBulkCopy tarafından Valuekullanılan kuralları kullanarak her kaynak değeri hedef veri türüne dönüştürmeyi dener. Dönüştürmeler performansı etkileyebilir ve beklenmeyen hatalara neden olabilir. Örneğin, bir Double veri türü çoğu zaman bir Decimal veri türüne dönüştürülebilir, ancak her zaman dönüştürülemez.

Örnek

Aşağıdaki konsol uygulaması, sınıfını kullanarak verilerin nasıl yükleneceklerini SqlBulkCopy gösterir. Bu örnekte, SQL Server AdventureWorks veritabanındaki Production.Product tablosundaki verileri aynı veritabanındaki benzer bir tabloya kopyalamak için kullanılırSqlDataReader.

Önemli

İş tablolarını Toplu Kopyalama Örneği Kurulumu'nda açıklandığı gibi oluşturmadığınız sürece bu örnek ç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ğinde bulunuyorsa, verileri kopyalamak için Transact-SQL INSERT … SELECT deyimi kullanmak daha kolay ve daha hızlıdır.

using System.Data.SqlClient;

static class Program
{
    static void Main()
    {
        var connectionString = GetConnectionString();
        // Open a sourceConnection to the AdventureWorks database.
        using (SqlConnection sourceConnection =
                   new(connectionString))
        {
            sourceConnection.Open();

            // Perform an initial count on the destination table.
            SqlCommand commandRowCount = new(
                "SELECT COUNT(*) FROM " +
                "dbo.BulkCopyDemoMatchingColumns;",
                sourceConnection);
            long countStart = Convert.ToInt32(
                commandRowCount.ExecuteScalar());
            Console.WriteLine("Starting row count = {0}", countStart);

            // Get data from the source table as a SqlDataReader.
            SqlCommand commandSourceData = new(
                "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(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(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 = 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();
            }
        }
    }

    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

Transact-SQL ve Komut Sınıfı Kullanarak Toplu Kopyalama İşlemi Gerçekleştirme

Aşağıdaki örnekte BULK INSERT deyimini ExecuteNonQuery yürütmek için yönteminin nasıl kullanılacağı gösterilmektedir.

Not

Veri kaynağının dosya yolu sunucuya göredir. Toplu kopyalama işleminin başarılı olması için sunucu işleminin bu yola erişimi olmalıdır.

Using connection As SqlConnection = New SqlConnection(connectionString)
Dim queryString As String = _
    "BULK INSERT Northwind.dbo.[Order Details] FROM " & _
    "'f:\mydata\data.tbl' WITH (FORMATFILE='f:\mydata\data.fmt' )"
connection.Open()
SqlCommand command = New SqlCommand(queryString, connection);

command.ExecuteNonQuery()
End Using
using (SqlConnection connection = New SqlConnection(connectionString))
{
string queryString =  "BULK INSERT Northwind.dbo.[Order Details] " +
    "FROM 'f:\mydata\data.tbl' " +
    "WITH ( FORMATFILE='f:\mydata\data.fmt' )";
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);

command.ExecuteNonQuery();
}

Ayrıca bkz.