Bagikan melalui


SqlBulkCopy.WriteToServer Metode

Definisi

Overload

WriteToServer(DbDataReader)

Menyalin semua baris dari array yang disediakan DbDataReader ke tabel tujuan yang ditentukan oleh DestinationTableName properti SqlBulkCopy objek.

WriteToServer(DataRow[])

Menyalin semua baris dari array yang disediakan DataRow ke tabel tujuan yang ditentukan oleh DestinationTableName properti SqlBulkCopy objek.

WriteToServer(DataTable)

Menyalin semua baris dalam yang disediakan DataTable ke tabel tujuan yang ditentukan oleh DestinationTableName properti SqlBulkCopy objek.

WriteToServer(IDataReader)

Menyalin semua baris dalam yang disediakan IDataReader ke tabel tujuan yang ditentukan oleh DestinationTableName properti SqlBulkCopy objek.

WriteToServer(DataTable, DataRowState)

Menyalin hanya baris yang cocok dengan status baris yang disediakan dalam tabel DataTable tujuan yang ditentukan oleh DestinationTableName properti SqlBulkCopy objek.

WriteToServer(DbDataReader)

Menyalin semua baris dari array yang disediakan DbDataReader ke tabel tujuan yang ditentukan oleh DestinationTableName properti SqlBulkCopy objek.

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)

Parameter

reader
DbDataReader

Baris DbDataReader yang akan disalin ke tabel tujuan.

Pengecualian

SqlBulkCopyColumnOrderHint tidak menentukan nama kolom tujuan yang valid.

Berlaku untuk

WriteToServer(DataRow[])

Menyalin semua baris dari array yang disediakan DataRow ke tabel tujuan yang ditentukan oleh DestinationTableName properti SqlBulkCopy objek.

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())

Parameter

rows
DataRow[]

Array DataRow objek yang akan disalin ke tabel tujuan.

Pengecualian

SqlBulkCopyColumnOrderHint tidak menentukan nama kolom tujuan yang valid.

Contoh

Aplikasi konsol berikut menunjukkan cara memuat data secara massal dari DataRow array. Tabel tujuan adalah tabel dalam database AdventureWorks .

Dalam contoh ini, DataTable dibuat pada durasi. Satu baris dipilih dari untuk disalin DataTable ke tabel tujuan.

Penting

Sampel ini tidak akan berjalan kecuali Anda telah membuat tabel kerja seperti yang dijelaskan dalam Penyiapan Contoh Salinan Massal. Kode ini disediakan untuk mendemonstrasikan sintaks untuk menggunakan SqlBulkCopy saja. Jika tabel sumber dan tujuan berada dalam instans SQL Server yang sama, lebih mudah dan lebih cepat untuk menggunakan pernyataan Transact-SQL INSERT … SELECT untuk menyalin data.

Keterangan

Saat operasi penyalinan massal sedang berlangsung, tujuan SqlConnection terkait sibuk melayaninya, dan tidak ada operasi lain yang dapat dilakukan pada koneksi.

Koleksi ColumnMappings memetakan dari DataRow kolom ke tabel database tujuan.

Berlaku untuk

WriteToServer(DataTable)

Menyalin semua baris dalam yang disediakan DataTable ke tabel tujuan yang ditentukan oleh DestinationTableName properti SqlBulkCopy objek.

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)

Parameter

table
DataTable

Baris DataTable yang akan disalin ke tabel tujuan.

Pengecualian

SqlBulkCopyColumnOrderHint tidak menentukan nama kolom tujuan yang valid.

Contoh

Aplikasi Konsol berikut menunjukkan cara memuat data secara massal dari DataTable. Tabel tujuan adalah tabel dalam database AdventureWorks .

Dalam contoh ini, DataTable dibuat pada durasi dan merupakan sumber SqlBulkCopy operasi.

Penting

Sampel ini tidak akan berjalan kecuali Anda telah membuat tabel kerja seperti yang dijelaskan dalam Penyiapan Contoh Salinan Massal. Kode ini disediakan untuk mendemonstrasikan sintaks untuk menggunakan SqlBulkCopy saja. Jika tabel sumber dan tujuan berada dalam instans SQL Server yang sama, lebih mudah dan lebih cepat untuk menggunakan pernyataan Transact-SQL INSERT … SELECT untuk menyalin data.

using Microsoft.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;";
    }
}

Keterangan

Semua baris dalam disalin DataTable ke tabel tujuan kecuali yang telah dihapus.

Saat operasi penyalinan massal sedang berlangsung, tujuan SqlConnection terkait sibuk melayaninya, dan tidak ada operasi lain yang dapat dilakukan pada koneksi.

Koleksi ColumnMappings memetakan dari DataTable kolom ke tabel database tujuan.

Lihat juga

Berlaku untuk

WriteToServer(IDataReader)

Menyalin semua baris dalam yang disediakan IDataReader ke tabel tujuan yang ditentukan oleh DestinationTableName properti SqlBulkCopy objek.

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)

Parameter

reader
IDataReader

Baris IDataReader yang akan disalin ke tabel tujuan.

Pengecualian

SqlBulkCopyColumnOrderHint tidak menentukan nama kolom tujuan yang valid.

Contoh

Aplikasi konsol berikut menunjukkan cara memuat data secara massal dari SqlDataReader. Tabel tujuan adalah tabel dalam database AdventureWorks .

Penting

Sampel ini tidak akan berjalan kecuali Anda telah membuat tabel kerja seperti yang dijelaskan dalam Penyiapan Contoh Salinan Massal. Kode ini disediakan untuk mendemonstrasikan sintaks untuk menggunakan SqlBulkCopy saja. Jika tabel sumber dan tujuan berada dalam instans SQL Server yang sama, lebih mudah dan lebih cepat untuk menggunakan pernyataan Transact-SQL INSERT … SELECT untuk menyalin data.

using Microsoft.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;";
    }
}

Keterangan

Operasi salin dimulai pada baris berikutnya yang tersedia di pembaca. Sebagian besar waktu, pembaca baru saja dikembalikan oleh ExecuteReader() atau panggilan serupa, sehingga baris berikutnya yang tersedia adalah baris pertama. Untuk memproses beberapa hasil, panggil NextResult() pembaca data dan panggil WriteToServer lagi.

Perhatikan bahwa menggunakan WriteToServer memodifikasi status pembaca. Metode ini akan memanggil Read() sampai mengembalikan false, operasi dibatalkan, atau terjadi kesalahan. Ini berarti bahwa pembaca data akan berada dalam status yang berbeda, mungkin di akhir tataan hasil, ketika WriteToServer operasi selesai.

Saat operasi penyalinan massal sedang berlangsung, tujuan SqlConnection terkait sibuk melayaninya, dan tidak ada operasi lain yang dapat dilakukan pada koneksi.

Kumpulan ColumnMappings memetakan dari kolom pembaca data ke tabel database tujuan.

Berlaku untuk

WriteToServer(DataTable, DataRowState)

Menyalin hanya baris yang cocok dengan status baris yang disediakan dalam tabel DataTable tujuan yang ditentukan oleh DestinationTableName properti SqlBulkCopy objek.

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)

Parameter

table
DataTable

Baris DataTable yang akan disalin ke tabel tujuan.

rowState
DataRowState

Nilai dari DataRowState enumerasi. Hanya baris yang cocok dengan status baris yang disalin ke tujuan.

Pengecualian

SqlBulkCopyColumnOrderHint tidak menentukan nama kolom tujuan yang valid.

Contoh

Aplikasi Konsol berikut menunjukkan cara memuat secara massal hanya baris dalam DataTable status yang cocok dengan status tertentu. Dalam hal ini, hanya baris yang tidak berubah yang ditambahkan. Tabel tujuan adalah tabel dalam database AdventureWorks .

Dalam contoh ini, DataTable dibuat pada durasi dan tiga baris ditambahkan ke dalamnya. WriteToServer Sebelum metode dijalankan, salah satu baris diedit. Metode WriteToServer ini dipanggil dengan DataRowState.UnchangedrowState argumen, jadi hanya dua baris yang tidak berubah yang disalin secara massal ke tujuan.

Penting

Sampel ini tidak akan berjalan kecuali Anda telah membuat tabel kerja seperti yang dijelaskan dalam Penyiapan Contoh Salinan Massal. Kode ini disediakan untuk mendemonstrasikan sintaks untuk menggunakan SqlBulkCopy saja. Jika tabel sumber dan tujuan berada dalam instans SQL Server yang sama, lebih mudah dan lebih cepat untuk menggunakan pernyataan Transact-SQL INSERT … SELECT untuk menyalin data.

using Microsoft.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;";
    }
}

Keterangan

Hanya baris dalam DataTable yang ada dalam status yang ditunjukkan dalam rowState argumen dan belum dihapus yang disalin ke tabel tujuan.

Catatan

Jika Deleted ditentukan, baris , Added, dan Modified apa pun Unchangedjuga akan disalin ke server. Tak terkecuali yang akan diangkat.

Saat operasi penyalinan massal sedang berlangsung, tujuan SqlConnection terkait sibuk melayaninya, dan tidak ada operasi lain yang dapat dilakukan pada koneksi.

Koleksi ColumnMappings memetakan dari DataTable kolom ke tabel database tujuan.

Berlaku untuk