Sql批量插入方法
时间:2021-07-01 10:21:17
帮助过:18人阅读
<summary>
/// 批量插入
/// </summary>
/// <typeparam name="T">泛型集合的类型</typeparam>
/// <param name="conn">连接对象</param>
/// <param name="tableName">将泛型集合插入到本地数据库表的表名</param>
/// <param name="list">要插入大泛型集合</param>
public static void BulkInsert<T>(SqlConnection conn,
string tableName, IList<T>
list)
{
using (
var bulkCopy =
new SqlBulkCopy(conn))
{
bulkCopy.BatchSize =
list.Count;
bulkCopy.DestinationTableName =
tableName;
var table =
new DataTable();
var props = TypeDescriptor.GetProperties(
typeof(T))
.Cast<PropertyDescriptor>
()
.Where(propertyInfo => propertyInfo.PropertyType.Namespace.Equals(
"System"))
.ToArray();
foreach (
var propertyInfo
in props)
{
bulkCopy.ColumnMappings.Add(propertyInfo.Name, propertyInfo.Name);
table.Columns.Add(propertyInfo.Name, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ??
propertyInfo.PropertyType);
}
var values =
new object[props.Length];
foreach (
var item
in list)
{
for (
var i =
0; i < values.Length; i++
)
{
values[i] =
props[i].GetValue(item);
}
table.Rows.Add(values);
}
bulkCopy.WriteToServer(table);
}
}
}
Sql批量插入方法
标签:pac type info color 数据 ace nullable ops row