关闭

asp.net事务处理范例

465人阅读 评论(0) 收藏 举报
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();
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3490次
    • 积分:56
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:3篇
    • 译文:0篇
    • 评论:0条
    文章存档