gpt4 book ai didi

c# - 如何在 C# 中做更快的插入查询?

转载 作者:行者123 更新时间:2023-12-03 22:00:31 27 4
gpt4 key购买 nike

我想将所有 id 插入到一个 sql 表中。以下方法有效,但这需要很长时间。执行此操作以提高速度的最佳或更好方法是什么。

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
string query = "";
foreach (var id in ids) // count = 60000
{
{
query += "INSERT INTO [table] (id) VALUES (" + id + ");";
}
}

SqlCommand command = new SqlCommand(query, connection);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
reader.Close();
}
connection.Close();
}

最佳答案

您可以使用 SqlBulkCopy 插入大量数据 - 如下所示:

// define a DataTable with the columns of your target table
DataTable tblToInsert = new DataTable();
tblToInsert.Columns.Add(new DataColumn("SomeValue", typeof (int)));

// insert your data into that DataTable
for (int index = 0; index < 60000; index++)
{
DataRow row = tblToInsert.NewRow();
row["SomeValue"] = index;
tblToInsert.Rows.Add(row);
}

// set up your SQL connection
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
{
// define your SqlBulkCopy
SqlBulkCopy bulkCopy = new SqlBulkCopy(connection);

// give it the name of the destination table WHICH MUST EXIST!
bulkCopy.DestinationTableName = "BulkTestTable";

// measure time needed
Stopwatch sw = new Stopwatch();
sw.Start();

// open connection, bulk insert, close connection
connection.Open();
bulkCopy.WriteToServer(tblToInsert);
connection.Close();

// stop time measurement
sw.Stop();
long milliseconds = sw.ElapsedMilliseconds;
}

在我的系统(PC、32GB RAM、SQL Server 2014)上,我在 135 - 185 毫秒内插入了 60'000 行。

关于c# - 如何在 C# 中做更快的插入查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31720826/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com