SqlBulkCopy批量添加

        /// <summary>
/// 添加数据
/// 注:DataTable列名必须和数据库列名一致
/// </summary>
/// <returns></returns>
public bool AddData()
{
var entityType = typeof(UserMessage);
var dataTable = new DataTable(entityType.Name);
foreach (var prop in entityType.GetProperties())
{
dataTable.Columns.Add(new DataColumn(prop.Name, prop.PropertyType));
} var row = dataTable.NewRow();
row["ID"] = ;
row["Name"] = "消息公告";
row["Type"] = Const.Bestone.TYPE1;
dataTable.Rows.Add(row); return DataTableCopy(dataTable, "数据库连接");
}      #region SqlBulkCopy批量添加 /// <summary>
/// 自增长表的插入
/// </summary>
/// <param name="dt"></param>
/// <param name="connectionString"></param>
public bool DataTableCopy(DataTable dt, string connectionString)
{
return this.DataTableCopy(dt, connectionString, SqlBulkCopyOptions.Default);
} /// <summary>
/// 非自增长表的插入
/// </summary>
/// <param name="dt"></param>
/// <param name="connectionString"></param>
/// <param name="copyOptions"></param>
public bool DataTableCopy(DataTable dt, string connectionString, SqlBulkCopyOptions copyOptions)
{
try
{
using (var sbc = new SqlBulkCopy(connectionString, copyOptions))
{
sbc.DestinationTableName = dt.TableName;
sbc.BatchSize = ; foreach (DataColumn col in dt.Columns)
{
sbc.ColumnMappings.Add(col.ColumnName, col.ColumnName);
} sbc.WriteToServer(dt);
} return true;
}
catch (Exception ex)
{
ex.SqlErrorLog(ex.Message, "自增长表的插入", "SqlServerHelp.DataTableCopy()");
return false;
}
} #endregion
上一篇:2017-12-15python全栈9期第二天第七节之x or y ,x 为 非 0时,则返回x


下一篇:!important的用法