Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
ICSM Computer
12-Feb-2025The
SqlBulkCopyclass in C# allows you to efficiently bulk insert large amounts of data into a SQL Server database. This is much faster than inserting rows individually usingINSERTstatements.1. Why Use SqlBulkCopy?
INSERTstatements.2. Basic Usage
Here's a basic example of how to use
SqlBulkCopyto insert data from aDataTableinto SQL Server.Example: Bulk Insert from DataTable
ColumnMappingsto match DataTable columns with SQL table columns.3. Data Sources for SqlBulkCopy
DataTableIDataReader(likeSqlDataReader)DataRow[](array of DataRows)Example: Bulk Insert from SqlDataReader
Efficient for transferring data between databases.
4. Performance Optimization
4.1. BatchSize
Set
BatchSizeto control how many rows are inserted per batch.Prevents memory overload for large datasets.
4.2. Enable Table Locking
Use
SqlBulkCopyOptions.TableLockfor faster inserts.Improves performance in high-volume inserts.
4.3. Set Timeouts for Large Data
Avoid timeout errors for large inserts.
5. Error Handling
SQL Server constraints (e.g., unique constraints) may cause errors. Use
SqlBulkCopywithtry-catch.6. Summary
DataTable,IDataReaderColumnMappingsif column names differBatchSize,TableLock, andBulkCopyTimeout