[英]Insert more than 1000 rows in SQL table
I have code that gets thousands of object ids from a website and I noticed that I was only able to write up to 1000 rows in a SQL Table using this code. 我有从网站获取数千个对象ID的代码,我注意到使用此代码我最多只能在SQL表中写入1000行。 How do write more than 1000 rows into a SQL table? 如何在SQL表中写入1000多个行? The data I am inserting the table is not coming from another database, it is dynamically generated from other code. 我要插入表的数据不是来自另一个数据库,而是从其他代码动态生成的。
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;
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);
}
Try to open and close the connection outside your loop, like this: 尝试打开和关闭循环外的连接,如下所示:
conn.Open();
foreach (var pair in webidsAndXPaths)
{
//your code here
}
conn.Close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.