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 通过泛型数组批量插入,布布扣,bubuko.com

SqlBulkCopy 通过泛型数组批量插入

上一篇:Security——Token认证


下一篇:SQL SERVER 导出到Oracle 问题与技巧