我的代码从网站上获取了数千个对象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;
答案 0 :(得分:2)
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);
}
答案 1 :(得分:-4)
尝试打开和关闭循环外的连接,如下所示:
conn.Open();
foreach (var pair in webidsAndXPaths)
{
//your code here
}
conn.Close();