اینم یه نمونه کد
protected void Button1_Click(object sender, EventArgs e)
{ SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;uid=sa;pwd=sa;");
myConnection.Open();
// Start a local transaction
SqlTransaction myTrans = myConnection.BeginTransaction();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;
try
{ myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "delete * from Region where RegionID=101";
// Attempt to commit the transaction.
myCommand.ExecuteNonQuery();
myTrans.Commit();
Response.Write("Both records are written to database.");
}
catch (Exception ep)
{ // Attempt to roll back the transaction.
myTrans.Rollback();
Response.Write(ep.ToString());
Response.Write("Neither record was written to database.");
}
finally
{ myConnection.Close();
}
}
خوب حالا من اینجا باید دستورات delete خودمو بنویسم درسته؟ الان باید یه sqlcomment بنویسم واسه پاک کردن از جدول 1 و یکی دیگه هم بنویسم واسه پاک کردن از جدول دو؟ یه چیزایی شبیه کد زیر؟
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection(@"Data Source=.\sqlexpress;initial catalog = allTest;integrated Security=true");
myConnection.Open();
SqlTransaction myTrans = myConnection.BeginTransaction();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
myCommand.Transaction = myTrans;
try
{
myCommand.CommandText = "delete * from table1 where id=4";
myCommand.ExecuteNonQuery();
myCommand.CommandText = "delete * from table2 where id=4";
myCommand.ExecuteNonQuery();
myTrans.Commit();
Response.Write("Both records are written to database.");
}
catch (Exception ep)
{
myTrans.Rollback();
Response.Write(ep.ToString());
Response.Write("Neither record was written to database.");
}
finally
{
myConnection.Close();
}
}