C# 在SQL表中插入1000多行

C# 在SQL表中插入1000多行,c#,sql,sql-server,C#,Sql,Sql Server,我有一段代码可以从一个网站上获取数千个对象ID,我注意到,使用这段代码,我只能在一个SQL表中写入多达1000行。如何将1000多行写入SQL表?我在表中插入的数据不是来自另一个数据库,而是从其他代码动态生成的 var conn = new SqlConnection(masterData.DictRunData["ConnectionStringLocalDb"]); const string objectName = "NotAvailable"; var dt = DateTime.Now

我有一段代码可以从一个网站上获取数千个对象ID,我注意到,使用这段代码,我只能在一个SQL表中写入多达1000行。如何将1000多行写入SQL表?我在表中插入的数据不是来自另一个数据库,而是从其他代码动态生成的

var conn = new SqlConnection(masterData.DictRunData["ConnectionStringLocalDb"]);
const string objectName = "NotAvailable";
var dt = DateTime.Now;
var cmd = new SqlCommand("insert into CorporateDataStructure.dbo.ObjectInventory (location, object_name, object_id, object_xpath, time) values (@location, @object_name, @object_id, @object_xpath, @time)", conn);

foreach (var pair in webidsAndXPaths)
{
    conn.Open();
    cmd.Parameters.Clear();
    cmd.Parameters.Add(new SqlParameter("@object_name", objectName));
    cmd.Parameters.Add(new SqlParameter("@object_id", pair.Key));
    cmd.Parameters.Add(new SqlParameter("@object_xpath", pair.Value));
    cmd.Parameters.Add(new SqlParameter("@time", dt));

    cmd.ExecuteNonQuery();
    conn.Close();
}
return true;

尝试在循环外部打开和关闭连接,如下所示:

conn.Open();
foreach (var pair in webidsAndXPaths)
{
    //your code here
}
conn.Close();

<代码>如何将多于1000行写入SQL表?< /代码>——在<代码> WebIDStxxPrase中有超过1000个元素,如果您想用大容量插入来执行任何类型的性能,则应该使用。考虑使用相同的连接来进行大容量插入,而不是使用每个插入的打开和关闭连接。您还应该查找
SqlBulkCopy
为什么只有1000行?乍一看,没有什么能说明你做的事情不能超过1000件。
var conn = new SqlConnection(masterData.DictRunData["ConnectionStringLocalDb"]);
            const string objectName = "NotAvailable";
            var dateTime = DateTime.Now;

            // create the datatable
            var table = new DataTable();
            table.Columns.Add("location", typeof(string));
            table.Columns.Add("object_name", typeof(string));
            table.Columns.Add("object_id", typeof(string));
            table.Columns.Add("object_xpath", typeof(string));
            table.Columns.Add("time", typeof (DateTime));

            // then loop all dictionary entries and add the rows
            foreach (var pair in webidsAndXPaths)
            {
                table.Rows.Add(location, objectName, pair.Key, pair.Value, dateTime);
            }

            // finally write the data to the sql server
            using (var bulkCopy = new SqlBulkCopy(conn))
            {
                conn.Open();
                bulkCopy.DestinationTableName = "dbo.ObjectInventory";
                bulkCopy.WriteToServer(table);
            }