狠狠色丁香婷婷综合尤物/久久精品综合一区二区三区/中国有色金属学报/国产日韩欧美在线观看 - 国产一区二区三区四区五区tv

LOGO OA教程 ERP教程 模切知識交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

C# .NET — SQL Bulk Insert 批量寫入

admin
2024年11月26日 0:10 本文熱度 854

在處理大量數(shù)據(jù)插入時,SQL Bulk Insert是一種高效的方法。本文將介紹如何在C# .NET中使用SQL Bulk Insert,并提供多個實(shí)用示例。

1. 基本的Bulk Insert操作

首先,讓我們看一個基本的Bulk Insert操作示例:

public class BulkInsertExample{    public void PerformBulkInsert(List<Customer> customers, string connectionString)    {        try        {            using (var connection = new SqlConnection(connectionString))            {                connection.Open();
               using (var bulkCopy = new SqlBulkCopy(connection))                {                    // 設(shè)置目標(biāo)表名                      bulkCopy.DestinationTableName = "Customers";
                   // 設(shè)置批量插入的大小                      bulkCopy.BatchSize = 1000;
                   // 映射列名                      bulkCopy.ColumnMappings.Add("Id", "Id");                    bulkCopy.ColumnMappings.Add("Name", "Name");                    bulkCopy.ColumnMappings.Add("Email", "Email");
                   // 設(shè)置超時時間                      bulkCopy.BulkCopyTimeout = 600; // 10分鐘  
                   var dataTable = ConvertToDataTable(customers);                    bulkCopy.WriteToServer(dataTable);                }            }        }        catch (Exception ex)        {            // 處理異常              Console.WriteLine($"批量插入時發(fā)生錯誤: {ex.Message}");            throw;        }    }
   private DataTable ConvertToDataTable(List<Customer> customers)    {        var dataTable = new DataTable();
       // 添加列          dataTable.Columns.Add("Id", typeof(int));        dataTable.Columns.Add("Name", typeof(string));        dataTable.Columns.Add("Email", typeof(string));
       // 添加行          foreach (var customer in customers)        {            dataTable.Rows.Add(customer.Id, customer.Name, customer.Email);        }
       return dataTable;    }}
public class Customer{    public int Id { get; set; }    public string Name { get; set; }    public string Email { get; set; }}
// 使用示例  class Program{    static void Main(string[] args)    {        // 連接字符串          string connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"
       // 創(chuàng)建測試數(shù)據(jù)          var customers = new List<Customer>        {            new Customer { Id = 1, Name = "John Doe", Email = "john@example.com" },            new Customer { Id = 2, Name = "Jane Smith", Email = "jane@example.com" },            new Customer { Id = 3, Name = "Bob Johnson", Email = "bob@example.com" }        };
       // 創(chuàng)建BulkInsertExample實(shí)例          var bulkInsert = new BulkInsertExample();
       try        {            // 執(zhí)行批量插入              bulkInsert.PerformBulkInsert(customers, connectionString);            Console.WriteLine("批量插入成功完成!");        }        catch (Exception ex)        {            Console.WriteLine($"發(fā)生錯誤: {ex.Message}");        }    }}

這個例子展示了如何將Customer對象列表批量插入到數(shù)據(jù)庫中。

2. 使用異步方法

.NET 支持異步操作,這對于大量數(shù)據(jù)插入特別有用:

public async Task PerformBulkInsertAsync(List<Customer> customers, string connectionString){    using (var connection = new SqlConnection(connectionString))    {        await connection.OpenAsync();
       using (var bulkCopy = new SqlBulkCopy(connection))        {            bulkCopy.DestinationTableName = "Customers";            bulkCopy.BatchSize = 1000;
           var dataTable = ConvertToDataTable(customers);            await bulkCopy.WriteToServerAsync(dataTable);        }    }}

3. 映射列名

如果數(shù)據(jù)源的列名與目標(biāo)表不完全匹配,可以使用列映射:

public void PerformBulkInsertWithMapping(List<Customer> customers, string connectionString){    using (var connection = new SqlConnection(connectionString))    {        connection.Open();
       using (var bulkCopy = new SqlBulkCopy(connection))        {            bulkCopy.DestinationTableName = "Customers";            bulkCopy.BatchSize = 1000;
           bulkCopy.ColumnMappings.Add("Id", "CustomerId");            bulkCopy.ColumnMappings.Add("Name", "CustomerName");            bulkCopy.ColumnMappings.Add("Email", "CustomerEmail");
           var dataTable = ConvertToDataTable(customers);            bulkCopy.WriteToServer(dataTable);        }    }}

4. 使用事務(wù)

在批量插入過程中使用事務(wù)可以確保數(shù)據(jù)的一致性:

public void PerformBulkInsertWithTransaction(List<Customer> customers, string connectionString){    using (var connection = new SqlConnection(connectionString))    {        connection.Open();
       using (var transaction = connection.BeginTransaction())        {            try            {                using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction))                {                    bulkCopy.DestinationTableName = "Customers";                    bulkCopy.BatchSize = 1000;
                   var dataTable = ConvertToDataTable(customers);                    bulkCopy.WriteToServer(dataTable);                }
               transaction.Commit();            }            catch (Exception)            {                transaction.Rollback();                throw;            }        }    }}

5. 處理大量數(shù)據(jù)

對于非常大的數(shù)據(jù)集,可以考慮分批處理:

public async Task PerformLargeBulkInsertAsync(IEnumerable<Customer> customers, string connectionString, int batchSize = 10000){    using (var connection = new SqlConnection(connectionString))    {        await connection.OpenAsync();
       using (var bulkCopy = new SqlBulkCopy(connection))        {            bulkCopy.DestinationTableName = "Customers";            bulkCopy.BatchSize = batchSize;
           var dataTable = new DataTable();            dataTable.Columns.Add("Id", typeof(int));            dataTable.Columns.Add("Name", typeof(string));            dataTable.Columns.Add("Email", typeof(string));
           foreach (var batch in customers.Chunk(batchSize))            {                dataTable.Clear();                foreach (var customer in batch)                {                    dataTable.Rows.Add(customer.Id, customer.Name, customer.Email);                }
               await bulkCopy.WriteToServerAsync(dataTable);            }        }    }}

這個方法使用了C# 引入的Chunk方法來分批處理大量數(shù)據(jù)。

結(jié)論

SQL Bulk Insert是處理大量數(shù)據(jù)插入的有效方法。在.NET 中,我們可以利用異步編程、事務(wù)管理和批處理等特性來優(yōu)化批量插入操作。通過選擇適合您特定需求的方法,您可以顯著提高數(shù)據(jù)插入的性能和可靠性。


該文章在 2024/11/26 12:06:19 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點(diǎn)晴ERP是一款針對中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內(nèi)大量中小企業(yè)的青睞。
點(diǎn)晴PMS碼頭管理系統(tǒng)主要針對港口碼頭集裝箱與散貨日常運(yùn)作、調(diào)度、堆場、車隊(duì)、財務(wù)費(fèi)用、相關(guān)報表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點(diǎn),圍繞調(diào)度、堆場作業(yè)而開發(fā)的。集技術(shù)的先進(jìn)性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點(diǎn)晴WMS倉儲管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號管理軟件。
點(diǎn)晴免費(fèi)OA是一款軟件和通用服務(wù)都免費(fèi),不限功能、不限時間、不限用戶的免費(fèi)OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved