Best way to Bulk Insert from a C# DataTable

后端 未结 5 638
轻奢々
轻奢々 2020-12-01 09:29

I have a DataTable that I want to push to the DB. I want to be able to say like

myDataTable.update();

But after reading the M

相关标签:
5条回答
  • 2020-12-01 09:51
    string connectionString= ServerName + DatabaseName + SecurityType;
    using (SqlConnection connection = new SqlConnection(connectionString))
    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection)) {
        connection.Open();
        bulkCopy.DestinationTableName = "TableName";
        try {
            bulkCopy.WriteToServer(dataTableName);
        } catch (Exception e) {
            Console.Write(e.Message);
        }
    }
    

    Please note that the structure of the database table and the table name should be the same or it will throw an exception.

    0 讨论(0)
  • 2020-12-01 09:51

    Here's how I do it using a DataTable. This is a working piece of TEST code.

    using (SqlConnection con = new SqlConnection(connStr))
    {
        con.Open();
    
        // Create a table with some rows. 
        DataTable table = MakeTable();
    
        // Get a reference to a single row in the table. 
        DataRow[] rowArray = table.Select();
    
        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
        {
            bulkCopy.DestinationTableName = "dbo.CarlosBulkTestTable";
    
            try
            {
                // Write the array of rows to the destination.
                bulkCopy.WriteToServer(rowArray);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
    
        }
    
    }//using
    
    0 讨论(0)
  • 2020-12-01 10:08

    This is going to be largely dependent on the RDBMS you're using, and whether a .NET option even exists for that RDBMS.

    If you're using SQL Server, use the SqlBulkCopy class.

    For other database vendors, try googling for them specifically. For example a search for ".NET Bulk insert into Oracle" turned up some interesting results, including this link back to Stack Overflow: Bulk Insert to Oracle using .NET.

    0 讨论(0)
  • 2020-12-01 10:08

    SqlBulkCopy class is best for SQL server,

    Doing Bulk Upload/Insert of DataTable to a Table in SQL server in C#

    0 讨论(0)
  • 2020-12-01 10:13

    If using SQL Server, SqlBulkCopy.WriteToServer(DataTable)

    • SqlBulkCopy.WriteToServer Method (DataTable)

    Or also with SQL Server, you can write it to a .csv and use BULK INSERT

    • BULK INSERT (Transact-SQL)

    If using MySQL, you could write it to a .csv and use LOAD DATA INFILE

    • LOAD DATA INFILE Syntax

    If using Oracle, you can use the array binding feature of ODP.NET

    • Bulk Insert to Oracle using .NET

    If SQLite:

    • How do I bulk insert with SQLite?
    • Faster bulk inserts in sqlite3?
    0 讨论(0)
提交回复
热议问题