Best way to Bulk Insert from a C# DataTable

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

提交回复
热议问题