asp.net事務處理範例

SqlConnection myConnection = new SqlConnection("Server=localhost;Database=***;uid=***;pwd=***;");
myConnection.Open();
// 啓動一個事務
SqlTransaction myTrans = myConnection.BeginTransaction();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection=myConnection;
// 爲事務創建一個命令
myCommand.Transaction = myTrans;
try
{
  myCommand.CommandText = "Insert into class_title (title_name, num) VALUES (100, '100')";
  myCommand.ExecuteNonQuery();
  myCommand.CommandText = "Insert into class_title (title_name, num) VALUES (101, '100')";
  myCommand.ExecuteNonQuery();
  myTrans.Commit();
  Response.Write("Both records are written to database.");
}
catch(Exception d)
{
  myTrans.Rollback();
  Response.Write(d.ToString());
  Response.Write("Neither record was written to database.");
}
finally
{
  myConnection.Close();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章