如何在 C# 中进行更快的插入查询?

use*_*681 2 c# sql sql-server

我想将所有 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();
}
Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 5

您可以使用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;
}
Run Code Online (Sandbox Code Playgroud)

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