SqlBulkCopy 通过泛型数组批量插入

public void SqlBulkCopy<T>(string tablename, List<T> list)
{
Type recordType = typeof(T);
PropertyInfo[] patternPInfos = recordType.GetProperties();
using (SqlConnection conn2 = new SqlConnection(connString))
{
using (SqlBulkCopy bcp = new SqlBulkCopy(conn2))
{
bcp.DestinationTableName = tablename;
DataTable tempdt = new DataTable();
foreach (var propertyInfo in patternPInfos)
{
tempdt.Columns.Add(propertyInfo.Name, propertyInfo.PropertyType);
}

foreach (var entity in list)
{
DataRow dr = tempdt.NewRow();

foreach (var propertyInfo in patternPInfos)
{
dr[propertyInfo.Name] = propertyInfo.GetValue(entity, null);

}
tempdt.Rows.Add(dr);
}
conn2.Open();
bcp.WriteToServer(tempdt);
conn2.Close();
}
}
}

===============

public T Analyze<T>(string html)
{

if (string.IsNullOrEmpty(html))
throw new Exception("传入的Html为空");

//反射
//TODO:增加缓存;
Type recordType = typeof(T);

Type patternType = this.GetType();
PropertyInfo[] patternPInfos = patternType.GetProperties();

//CreateInstance 创建指定泛型类型参数所指定类型的实例。

T record = Activator.CreateInstance<T>();

foreach (PropertyInfo patternPInfo in patternPInfos)
{
object[] customInfos = patternPInfo.GetCustomAttributes(typeof(PatternAttributes), true);
if (customInfos == null
|| customInfos.Length == 0)
continue;

PatternAttributes patternAtrributes = customInfos.GetValue(0) as PatternAttributes;

 

//propertyInfo.GetValue(entity,null) 获取实体的值 

object patternObjVal = patternType.GetProperty(patternPInfo.Name).GetValue(this, null);
if (patternObjVal == null)
continue;
RegexColumnEntity regexColumn = (RegexColumnEntity)patternObjVal;
//如果没有写规则则跳过
if (string.IsNullOrEmpty(regexColumn.Pattern))
continue;

//提取值

object objVal = Analyze(html, regexColumn, patternAtrributes);

PropertyInfo recordProperty = recordType.GetProperty(patternPInfo.Name);
if (recordProperty != null)
{
try
{
recordProperty.SetValue(record, objVal, null);
}
catch { }
}
}

return record;
}

SqlBulkCopy 通过泛型数组批量插入,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。