技术文章
当前位置:首页 > 技术文章

c#事务的使用,示例及注意事项

c#事务的使用,示例及注意事项
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connstr=ConfigurationManager.AppSettings["ConnectionString"].ToString();
SqlConnection con1 = new SqlConnection(connstr);
if (con1.State.Equals(ConnectionState.Closed))
{
con1.Open();
}
string sql1 = "insert into guestbook(title,body) values('事务添加1','事务添加1')";
SqlCommand cmd1 = new SqlCommand(sql1,con1);
//事务开始 当使用con1.BeginTransaction()后,那么每一个con1相关联的command命令都应该使用这个事务 因而当我们用cmd2时需要新创建一个con2
SqlTransaction myTran = con1.BeginTransaction();
cmd1.Transaction = myTran;
try
{
cmd1.ExecuteNonQuery();
string sql2 = "insert into guestbook(title,body) values('事务添加2','事务添加2')";
SqlConnection con2 = new SqlConnection(connstr);
if (con2.State.Equals(ConnectionState.Closed))
{
con2.Open();
}
SqlCommand cmd2 = new SqlCommand(sql2, con2);
cmd2.ExecuteNonQuery();
con2.Close();
myTran.Commit();
Response.Write("事务执行成功!");
}
catch
{
myTran.Rollback();
Response.Write("事务执行失败!");
}
finally
{
con1.Close();
}
}
}
}