TL;DR如果您的数据已经表示为DataTable,您可以使用SqlBulkCopy 将其插入到服务器上的目标表中:
string csDestination = "put here the a connection string to the database";
using (SqlConnection connection = new SqlConnection(csDestination))
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
connection.Open()
bulkCopy.DestinationTableName = "TUrls";
bulkCopy.WriteToServer(dataTableOfUrls);
}
如果您只想加载“10 到 50 个网址”,则无需使用 SqlBulkCopy - 它的一般用途是消除数千个单独的插入。
所以,插入不带 SqlBulkCopy [不带EntityFramework] 可以一一完成:
string insertQuery = "insert into TUrls(address, name) values(@address, @name)";
foreach (URL url in listOfUrls)
{
SqlCommand cmd = new SqlCommand(insertQuery);
cmd.Parameters.AddWithValue("@name", url.url_name);
cmd.Parameters.AddWithValue("@address", url.urld_address);
// Remember to take care of connection! I omit this part for clarity
cmd.ExecuteNonQuery();
}
要使用 SqlBulkCopy 插入数据,您需要将数据(例如自定义类对象列表)转换为 DataTable。以下是来自Marc Gravell's answer 的引用,作为此类转换的通用解决方案示例:
这是一个不错的 2013 年更新,使用
FastMember 来自 NuGet:
IEnumerable<SomeType> data = ...
DataTable table = new DataTable();
using(var reader = ObjectReader.Create(data)) {
table.Load(reader);
}
是的,这与this 几乎完全相反;
反思就足够了——或者如果你需要更快,
HyperDescriptor 在 2.0 中,或者在 3.5 中可能是 Expression。实际上,
HyperDescriptor 应该绰绰有余。
例如:
// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for(int i = 0 ; i < props.Count ; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
现在,将您的数据表示为DataTable,您就可以将其写入服务器上的目标表了:
string csDestination = "put here the a connection string to the database";
using (SqlConnection connection = new SqlConnection(csDestination))
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
connection.Open()
bulkCopy.DestinationTableName = "TUrls";
bulkCopy.WriteToServer(dataTableOfUrls);
}
希望对你有帮助。
UPD
- 回答@pseudonym27 问题:“您好,我可以使用 BulkCopy 类将数据附加到 SQL 数据库中的现有表吗?”
是的,您可以 - BulkCopy 的工作方式与插入命令一样,它会附加数据。
此外,考虑使用中间表以防操作出错的可能性很高(例如,插入时间长和连接问题),并且您希望尽可能少地忙/锁定目标表。当然,中间表的另一个用例是需要在插入之前进行一些数据转换。