InsertCommand、UpdateCommand批量插入和更新数据库数据,今天讲一下怎么用DeleteCommand批量删除数据库数据。
DeleteCommand操作要明确有dss.Tables[0].Rows[j].Delete()这个动作,才能成功删除数据。
延续前面的InsertCommand、UpdateCommand,直接上代码:(说明,我已经把从数据库取出的数据记录挑出了要删除的记录)
string day = XMLConfig.GetValue("appSettings", "add", "SyncDay", "value");
string dayTemp = (int.Parse(day) - 1).ToString();
DataSet dss = new DataSet();
adapter = new SqlDataAdapter(cmd);
commandBulider = new SqlCommandBuilder(adapter);
commandBulider.ConflictOption = ConflictOption.OverwriteChanges;
adapter.SelectCommand = new SqlCommand("select * from Shift where StartTime>dateadd(day,-" + dayTemp + ",CONVERT(varchar(100), GETDATE(), 23))", conn);//获得框架
adapter.DeleteCommand = new SqlCommand("delete from Shift where RTRIM(ShiftCode)=RTRIM(@ShiftCode)", conn);
adapter.DeleteCommand.Parameters.Add("@ShiftCode", SqlDbType.Char, 10, "ShiftCode");
adapter.DeleteCommand.Parameters.Add("@StartTime", SqlDbType.DateTime, 8, "StartTime");
adapter.DeleteCommand.Parameters.Add("@EndTime", SqlDbType.DateTime, 8, "EndTime");
adapter.DeleteCommand.Parameters.Add("@StartPlanDownTime", SqlDbType.DateTime, 8, "StartPlanDownTime");
adapter.DeleteCommand.Parameters.Add("@EndPlanDownTime", SqlDbType.DateTime, 8, "EndPlanDownTime");
adapter.DeleteCommand.Parameters.Add("@OvertimeBegin", SqlDbType.DateTime, 8, "OvertimeBegin");
adapter.DeleteCommand.Parameters.Add("@OvertimeEnd", SqlDbType.DateTime, 8, "OvertimeEnd");
adapter.DeleteCommand.Parameters.Add("@Overtime", SqlDbType.Decimal, 5, "Overtime");
adapter.DeleteCommand.Parameters.Add("@IsClosed", SqlDbType.Bit, 1, "IsClosed");
adapter.DeleteCommand.UpdatedRowSource = UpdateRowSource.None;
adapter.UpdateBatchSize = 0;
adapter.Fill(dss);
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (int j = dss.Tables[0].Rows.Count - 1; j >= 0; j--)
{
if (ds.Tables[0].Rows[i].ItemArray.GetValue(1).ToString().Trim() == dss.Tables[0].Rows[j].ItemArray.GetValue(1).ToString().Trim())
{
dss.Tables[0].Rows[j].Delete();
break;
}
}
}
try
{
int nn = adapter.Update(dss.Tables[0]);//返回影响的行数
}
catch (Exception e)
{
。。。//处理自己的异常操作
return false;
}
finally
{
dss.Dispose();
adapter.Dispose();
commandBulider.Dispose();
}
OK!可以删除数据了,试一下吧 --_--