循环写入Insert 与 SqlBulkcopy

时间:2022-01-28 14:18:45
/* Insert by Loop */
cmd.CommandText = "insert into BizSharedStore (BizSharedStoreId,BizSharedId,StoreCode,StartDt,EndDt) values (@BizSharedStoreId,@BizSharedId,@RuleCode);";
cmd.CommandType = CommandType.Text; foreach (var x in query_BizSharedList)
{
try
{
cmd.Parameters.Clear();
cmd.Parameters.Add("@BizSharedListId", SqlDbType.VarChar).Value = x.BizSharedListId.ToString();
cmd.Parameters.Add("@BizSharedId", SqlDbType.VarChar).Value = x.BizSharedId;
cmd.Parameters.Add("@RuleCode", SqlDbType.VarChar).Value = x.Rulecode;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Insert BizShardList Error:" + ex.Message);
} }
// End of Insert by Loop MessageBox.Show("insert into BizSharedList by Insert Loop, Successfully!");

SqlBulkcopy

                using (SqlBulkCopy bulk1 = new SqlBulkCopy(conn))
{
bulk1.DestinationTableName = "BizSharedList";
//bulk1.ColumnMappings.Add("BizSharedListId", "BizSharedListId");
//bulk1.ColumnMappings.Add("BizSharedId", "BizSharedId");
//bulk1.ColumnMappings.Add("RuleCode", "RuleCode");
bulk1.WriteToServer(tbl_BizSharedList);
} MessageBox.Show("Bulk Insert Table: BizSharedList Successfully!");

Loop Insert

    for (var i = ; i < _waypointList.Count; i++)
{
query +=
@"INSERT INTO waypoint
(booking_id, sequence, address, lat, lng, reference)
VALUES
((select id FROM booking WHERE reference=@reference" + i.ToString() + @"),
@sequence" + i.ToString() + @",
@address" + i.ToString() + @",
@lat" + i.ToString() + @",
@lng" + i.ToString() + @",
@reference" + i.ToString() + ")"; cmd.Parameters.AddWithValue(("@reference" + i.ToString()), _reference);
cmd.Parameters.AddWithValue(("@sequence" + i.ToString()), i);
cmd.Parameters.AddWithValue(("@address" + i.ToString()), _waypointList[i]);
cmd.Parameters.AddWithValue(("@lat" + i.ToString()), _lat);
cmd.Parameters.AddWithValue(("@lng" + i.ToString()), _lng);
}