方法1:DataTable方式
/// <summary>
/// 批量新增數(shù)據(jù)(限Excel使用)
/// </summary>
/// <param name="dt">DataTable(其中的列名要與數(shù)據(jù)庫(kù)表列名一致)</param>
public int BatchAdd(DataTable dt)
{
int rs = 1;
SqlConnection sqlConn =
new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
try
{
sqlConn.Open();
SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(sqlConn);
sqlbulkcopy.DestinationTableName = "PhoneToQRCode";//數(shù)據(jù)庫(kù)中的表名
sqlbulkcopy.WriteToServer(dt);
}
catch (Exception ex)
{
rs = 0;
}
finally
{
sqlConn.Close();
}
return rs;
}
方法2:使用List方式
/// <summary>
/// 批量插入
/// </summary>
/// <param name="conn"></param>
/// <param name="list">源數(shù)據(jù)</param>
internal static void BulkCopy<T>(IDbConnection conn, IEnumerable<T> list)
{
var dt = list.ToDataTable();
using (conn)
{
if (conn.State == ConnectionState.Closed)
conn.Open();
using (var sqlbulkcopy = new SqlBulkCopy((SqlConnection)conn))
{
sqlbulkcopy.DestinationTableName = dt.TableName;
for (var i = 0; i < dt.Columns.Count; i++)
{
sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
}
sqlbulkcopy.WriteToServer(dt);
}
}
}
/// <summary>
/// List轉(zhuǎn)DataTable
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list">集合</param>
/// <returns></returns>
public static DataTable ToDataTable<T>(this IEnumerable<T> list)
{
var type = typeof(T);
var properties = type.GetProperties().ToList();
var newDt = new DataTable(type.Name);
properties.ForEach(propertie =>
{
Type columnType;
if (propertie.PropertyType.IsGenericType && propertie.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
columnType = propertie.PropertyType.GetGenericArguments()[0];
}
else
{
columnType = propertie.PropertyType;
}
newDt.Columns.Add(propertie.Name, columnType);
});
foreach (var item in list)
{
var newRow = newDt.NewRow();
properties.ForEach(propertie =>
{
newRow[propertie.Name] = propertie.GetValue(item, null) ?? DBNull.Value;
});
newDt.Rows.Add(newRow);
}
return newDt;
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。