个人博客开始运营:点击进入我的博客
欢迎大家访问,以及收藏,内容会及时更新的!
C# 批量插入大量数据 SQL Server
//导入数据库数据
string connStr = "数据库连接串";
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connStr))
{
var type = typeof(T);
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(type);
foreach (PropertyDescriptor prop in props)
{
bulkCopy.ColumnMappings.Add(prop.Name, prop.Name);
}
bulkCopy.DestinationTableName = type.Name;
bulkCopy.WriteToServer(ToDataTable<T>(list));
}
//获取需要导入的DataTable
public DataTable ToDataTable<T>(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];
Type colType = prop.PropertyType;
if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>)))
{
colType = colType.GetGenericArguments()[0];
}
table.Columns.Add(prop.Name, colType);
}
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;
}