What’s the best way to bulk database inserts from c#?

前端 未结 10 2108
盖世英雄少女心
盖世英雄少女心 2020-12-02 14:22

How do I/what’s the best way to do bulk database inserts?

In C#, I am iterating over a collection and calling an insert stored procedure for each item in the collect

相关标签:
10条回答
  • 2020-12-02 14:58

    Create a XML document that contains all the items to be inserted. Then inside of a stored procedure, use the TSQL xml support (OPENXML) to read all the data from the XML document and insert it into your tables with hopefully one insert statement for each table.

    However if you are only inserting data into a single table and don’t need any database side logic, why not use SqlBulkCopy?

    0 讨论(0)
  • 2020-12-02 15:01

    The .NET SqlBulkCopy class works quite well.

    0 讨论(0)
  • 2020-12-02 15:02

    Well, 10 items isn't what I call bulk, but for larger sets, SqlBulkCopy is your friend. All you need to do is feed it either a DataTable or an IDataReader (my preferred option, 'cos I like streaming APIs). I did something similar here (you can ignore the xml side - just subclass the SimpleDataReader).

    0 讨论(0)
  • 2020-12-02 15:10

    CsharperGuyInLondon, here's a simple example of SqlBulkCopy code:

    using System.Data.SqlClient;
    
    DataTable table = new DataTable("States");
    // construct DataTable
    table.Columns.Add(new DataColumn("id_state", typeof(int))); 
    table.Columns.Add(new DataColumn("state_name", typeof(string)));
    
    // note: if "id_state" is defined as an identity column in your DB,
    // row values for that column will be ignored during the bulk copy
    table.Rows.Add("1", "Atlanta");
    table.Rows.Add("2", "Chicago");
    table.Rows.Add("3", "Springfield");
    
    using(SqlBulkCopy bulkCopy = new SqlBulkCopy(connectionString))
    {
      bulkCopy.BulkCopyTimeout = 600; // in seconds
      bulkCopy.DestinationTableName = "state";
      bulkCopy.WriteToServer(table);
    }
    
    0 讨论(0)
  • 2020-12-02 15:11

    You can build a BLOB (image) and send it as a parameter to a stored procedure. Inside the stored procedure, you can fetch all the items using substring().

    0 讨论(0)
  • 2020-12-02 15:11

    Here's a good example of SqlBulkCopy in action:

    http://blogs.msdn.com/nikhilsi/archive/2008/06/11/bulk-insert-into-sql-from-c-app.aspx

    0 讨论(0)
提交回复
热议问题