使用SqlBulkCopy类可以快速地将数据批量插入数据库。示例代码如下:
using System.Data.SqlClient;
// ...
// 定义连接字符串
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;";
// 定义插入的目标表名
string tableName = "myTable";
// 创建数据表并填充数据
DataTable table = new DataTable();
table.Columns.Add("Column1", typeof(int));
table.Columns.Add("Column2", typeof(string));
table.Rows.Add(1, "Value1");
table.Rows.Add(2, "Value2");
table.Rows.Add(3, "Value3");
// 使用SqlBulkCopy类将数据批量插入数据库
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
bulkCopy.DestinationTableName = tableName;
bulkCopy.WriteToServer(table);
}
}