Best way to Bulk Insert from a C# DataTable

后端 未结 5 673
轻奢々
轻奢々 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

    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
    

提交回复
热议问题