在 C# 中将动态行数插入 SQL 服务器的最佳方法是什么

What is the best way to Insert a dynamic number of rows into SQL Server in C#

我正在使用 C# 和 ADO.NET 将动态行数插入 SQL 服务器 table, 但我不确定这是最好的方法还是最有效的方法。

在阅读了不同的意见后,我使用了这种方式,但想确认这是否是一个好主意。

用的工具说好可以改

SqlConnection sc = DBManager.CreateConnection();
sc.Open();

foreach (string item in listSurfaceTypes)
{
    SqlCommand insert = new SqlCommand("INSERT INTO dbo.surface_type_inspection " +
                "(InspectionID, SurfaceType) VALUES (@InspecId, @SurfaceType)", sc);
    insert.Parameters.AddWithValue("@InspecId", id);
    insert.Parameters.AddWithValue("@SurfaceType", item);

    insert.ExecuteNonQuery();
}

sc.Close();

哦,顺便说一下,有多个 table,所以我必须重复多次,我应该为每个 table 打开和关闭连接,还是对所有使用相同的连接?

使用 SqlBulkCopy class,这样你就不会逐行插入,这样会慢得多。 https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlbulkcopy

在 SqlTransaction 中插入最少的批次,并将 SqlConnection 放入 using 块中。该事务确保行全部插入或 none 插入,并通过消除每行后的提交和日志刷新来提高性能。

using (var sc = DBManager.CreateConnection())
{
    sc.Open();
    var tran = sc.BeginTransaction();
    foreach (string item in listSurfaceTypes)
    {
        SqlCommand insert = new SqlCommand("INSERT INTO dbo.surface_type_inspection (InspectionID,SurfaceType) values(@InspecId,@SurfaceType)", sc);
        insert.Parameters.AddWithValue("@InspecId", id);
        insert.Parameters.AddWithValue("@SurfaceType", item);

        insert.Transaction = tran;
        insert.ExecuteNonQuery();
    }
    tran.Commit();
    sc.Close();
}

如果要插入数千行,SqlBulkCopy 的速度会明显加快。