Speed Up Database Inserts with SqlBulkCopy
Inserting large DataTables row-by-row is inefficient. The SqlBulkCopy
class offers a much faster solution for bulk data insertion into SQL Server databases.
First, establish a database connection. Then, create a SqlBulkCopy
object, providing the connection string. You can also customize options like identity column handling during creation.
Crucially, map your DataTable columns to the corresponding database table columns. If column names align, simply copy them into bulkCopy.ColumnMappings
. Otherwise, map them manually.
Finally, specify your target table and, optionally, a timeout, then call WriteToServer
. This single call performs the bulk insert, drastically improving performance over individual row inserts.
The above is the detailed content of How Can I Efficiently Insert a Large DataTable into a Database?. For more information, please follow other related articles on the PHP Chinese website!