我想将超过1000行的数据插入到SQL表中,因此我需要使用SqlBulkCopy。但是看起来我需要先创建一个DataTable。因此,如何将数据添加到DataTable?我想将字典中动态生成的数据添加到DataTable中。
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 :(得分:3)
将适当的列添加到DataTable
,然后循环所有字典条目并添加行:
var table = new System.Data.DataTable();
table.Columns.Add("object_name", typeof(string));
table.Columns.Add("object_id", typeof(int));
table.Columns.Add("object_xpath", typeof(string));
table.Columns.Add("time", typeof(DateTime));
foreach (var pair in webidsAndXPaths)
{
table.Rows.Add(objectName, pair.Key, pair.Value, dt);
}
您可以使用SetField
使用这种更长但可读的方法而不是table.Rows.Add
:
foreach (var pair in webidsAndXPaths)
{
DataRow row = table.Rows.Add();
row.SetField("object_name", objectName);
row.SetField("object_id", pair.Key);
row.SetField("object_xpath", pair.Value);
row.SetField("time", dt);
}
最后,您需要使用SqlBulkCopy.WriteToServer
:
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(conn))
{
conn.Open();
bulkCopy.DestinationTableName = "dbo.ObjectInventory";
bulkCopy.WriteToServer(table);
}
如果DataTable
中的列顺序与数据库中的列相同,则无需映射列。
答案 1 :(得分:2)
using (var bulkCopy = new SqlBulkCopy(conn, <SqlBulkCopyOptions>))
{
//dataTable definition
var table = new System.Data.DataTable();
table.Columns.Add("object_name", typeof(string));
table.Columns.Add("object_id", typeof(int));
table.Columns.Add("object_xpath", typeof(string));
table.Columns.Add("time", typeof(DateTime));
//bulkCopy options
bulkCopy.BatchSize = webidsAndXPaths.Count();
bulkCopy.DestinationTableName = "CorporateDataStructure.dbo.ObjectInventory";
//bulkCopy mappings (not mandatory, just to avoid depending on column ordering in datatable)
//That may avoid "strange" mistakes if you change something to your db or datatable.
bulkCopy.ColumnMappings.Add("object_name", "object_name");
bulkCopy.ColumnMappings.Add("object_id", "object_id");
bulkCopy.ColumnMappings.Add("object_xpath", "object_xpath");
bulkCopy.ColumnMappings.Add("time", "time");
//dataTable fedding from dictionary
foreach (var pair in webidsAndXPaths)
{
table.Rows.Add(objectName, pair.Key, pair.Value, dt);
}
//write to db.
bulkCopy.WriteToServer(table);
}