因为删除是对数据影响比较大的事情,所以在应用事要确定用户是否是真的删除,避免数据损失的方式是在执行操作时尽量不用Delete语句;
而是用update 语句使数据变成透明的,查询的时候检索不到这些“透明的数据”给用户的感觉是这些数据被删除了,实际上仍突然藏于数据库中,当有特殊需要时恢复这些数据,供用户使用,下面是我在做删除数据编写的代码,仅供参考:
protected void Button1_Click1(object sender, EventArgs e)
{
try
{
int aa = Convert.ToInt32(this.TextBox1.Text.Trim());
if (aa > 0)
{
//使用自定义方法删除数据
DeleteInfo(aa, true);
Label1.Text = "删除成功";
}
else
{
Label1.Text = "编号必须大于0";
}
}
catch
{
Label1.Text = "编号必须为数字";
}
}
//定义方法
public int DeleteInfo(int mm, Boolean isRealDelete)
{
string str="Server=SALIM-EUMKBNTPU//SQLEXPRESS; User id=salim; pwd=067919; DataBase=TB_01";
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand();
com.Connection = con;//使用存储过程
if (isRealDelete == false)
{
com.CommandText = string.Format("update dbo.Table_3 set IsDeleted='true' where bkid={0}",mm);
}
else if (isRealDelete == true)
{
com.CommandText = string.Format("delete from dbo.Table_3 where bkid={0}",mm);
}
int bb = 0;
try
{
con.Open();
bb = com.ExecuteNonQuery();
}
catch (Exception ex)
{
bb = 0;
throw new ApplicationException(ex.Message);//此处表若发生异常,则使受影响的行数为0,说明删除没有成功
}
finally
{
con.Close(); //关闭数据库连接
}
return bb; //返回受影响的行数;
}
在这里执行虚拟删除是,在数据表中设置一个isDeleted字段,设置其默认值为false
通过改字段将数据变成透明状态,执行查询操作时检索不到这些数据,让用户感觉数据被删除!