一直说事务事务的,明白咋用但一直都没用过。现在做删除图书的时候终于用到了,因为同时还要删除图书的分类。因为一本书有多个分类,因此把图书ID和分类ID单放到一个表里。删的时候先删这个表的数据(因为是外键表嘛~),再删图书表的数据。
/// <summary>
/// 删除一本图书
/// </summary>
/// <param name="iProductID">要删除的图书ID</param>
public int DeleteProduct(int iProductID)
{
int iRow = 0;
string strSql = String.Empty;
SqlCommand cmd = new SqlCommand();
SqlConnection conn = DBHelp.GetConnection();
SqlTransaction tran = conn.BeginTransaction();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Transaction = tran;
try
{
strSql = new StringBuilder()
.AppendFormat("DELETE FROM ProductCategory WHERE (ProductID = {0})", iProductID).ToString();
cmd.CommandText = strSql;
iRow = cmd.ExecuteNonQuery();
strSql = new StringBuilder()
.AppendFormat("DELETE FROM Product WHERE (ProductID = {0})", iProductID).ToString();
cmd.CommandText = strSql;
iRow = cmd.ExecuteNonQuery();
tran.Commit();
}
catch (Exception ex)
{
iRow = 0;
tran.Rollback();
}
finally
{
conn.Close();
}
return iRow;
}
/// <summary>
/// 删除一本图书
/// </summary>
/// <param name="iProductID">要删除的图书ID</param>
public int DeleteProduct(int iProductID)
{
int iRow = 0;
string strSql = String.Empty;
SqlCommand cmd = new SqlCommand();
SqlConnection conn = DBHelp.GetConnection();
SqlTransaction tran = conn.BeginTransaction();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Transaction = tran;
try
{
strSql = new StringBuilder()
.AppendFormat("DELETE FROM ProductCategory WHERE (ProductID = {0})", iProductID).ToString();
cmd.CommandText = strSql;
iRow = cmd.ExecuteNonQuery();
strSql = new StringBuilder()
.AppendFormat("DELETE FROM Product WHERE (ProductID = {0})", iProductID).ToString();
cmd.CommandText = strSql;
iRow = cmd.ExecuteNonQuery();
tran.Commit();
}
catch (Exception ex)
{
iRow = 0;
tran.Rollback();
}
finally
{
conn.Close();
}
return iRow;
}