由于工作中项目需求结算一次生成一批相同批次号的数据插入一个表中,然后再通过另一页面展示出来,所以需要用到一次性插入一批数据,所以就采用了SqlBulkCopy插入一批数据
1 public static int InsertSettlementRecord(SqlConnection connection, List<InventorySettlement> model)
{
DataTable dt = GetTableSchema();
SqlBulkCopy bulkCopy = new SqlBulkCopy(connection);//实例化SqlBulkCopy对象
bulkCopy.DestinationTableName = "Tuhu_shop.dbo.InventorySettlement";//需要插入的表的表名
bulkCopy.BatchSize = dt.Rows.Count;
string sql = "SELECT MAX(BatchNo) AS BatchNo FROM Tuhu_shop.dbo.InventorySettlement WITH (NOLOCK)";
var maxBatchNo = SqlHelper.ExecuteDataTable(connection, CommandType.Text, sql).ConvertTo<InventorySettlement>().ToList();//获得当前表中的最大批次号,以后每次添加的一批数据都在当前批次上加1,
int? maxBatch = ;
if (maxBatchNo[].BatchNo == null)//对批次号的判断
{
maxBatch = ;
}
else
{
maxBatch = maxBatchNo[].BatchNo;//对批次号赋值
} foreach (var item in model)//循环向datatable中插入数据
{
DataRow r = dt.NewRow();
r[] = item.ShopId;
r[] = item.PID;
r[] = item.PName;
r[] = item.SettlementCount;
r[] = item.SettlementPrice;
r[] = item.SumMoney;
r[] = item.SettlementStatus;
r[] = maxBatch+;
r[] = DateTime.Now;
r[] = item.Settlementor;
dt.Rows.Add(r); }
foreach (DataColumn dc in dt.Columns)
{
bulkCopy.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);//使列对应,这段代码很重要,自己亲测少了这一句会插入失败
} if (dt != null && dt.Rows.Count != )
{
bulkCopy.WriteToServer(dt);//通过SqlBulkCopy一次性插入到数据库表中
return ;
}
else
{
return ;
}
} 使用 SqlBulkCopy 类只能向 SQL Server 表写入数据。但是,数据源不限于 SQL Server;可以使用任何数据源,只要数据可加载到 DataTable 实例或可使用 IDataReader 实例读取数据。
来自 <http://www.cnblogs.com/zfanlong1314/archive/2013/02/05/2892998.html>
public static DataTable GetTableSchema()
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[]{
//new DataColumn("PKID",typeof(int)),
new DataColumn("ShopId",typeof(int)),
new DataColumn("PID",typeof(string)),
new DataColumn("PName",typeof(string)),
new DataColumn("SettlementCount",typeof(int)),
new DataColumn("SettlementPrice",typeof(decimal)),
new DataColumn("SumMoney",typeof(decimal)),
new DataColumn("SettlementStatus",typeof(bool)),
new DataColumn("BatchNo",typeof(int)),
new DataColumn("CreateDateTime",typeof(DateTime)),
new DataColumn("Settlementor",typeof(string))
}); return dt;
}
05-11 16:15