Sqlconnection conn=new Sqlconnection(str); //鏈接DB
Sqlcommand cmd=conn.CreateCommand(); //創建執行SQL命令對象
SqlTransaction ston; //創建事務對象
conn.open(); //打開鏈接
Ston=Conn.BeginTransaction(); //開始事務
cmd.Transaction=ston; //為一個即將發生的事物指派對象
try
{
cmd.executenonquery();
cmd.ExecuteNonQuery();
Sqlcommand cmd=conn.CreateCommand(); //創建執行SQL命令對象
SqlTransaction ston; //創建事務對象
conn.open(); //打開鏈接
Ston=Conn.BeginTransaction(); //開始事務
cmd.Transaction=ston; //為一個即將發生的事物指派對象
try
{
cmd.executenonquery();
cmd.ExecuteNonQuery();
......
ston.commit(); //提交事務
}
catch()
{
ston.RollBack(); //事務回滾
}
}
catch()
{
ston.RollBack(); //事務回滾
}
例子: protected void Page_Load(object sender, EventArgs e)
{
{
SqlConnection conn = new SqlConnectio("server=10.158.17.22\\LITIANXIANG;uid=sa;pwd=tianxiang;database=test;");
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
SqlCommand cmd = conn.CreateCommand();
cmd.Transaction = tran;
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
SqlCommand cmd = conn.CreateCommand();
cmd.Transaction = tran;
try
{
cmd.CommandText = "INSERT suggestion([Content],Reply,IsAnonymous,Lasteditby,Lasteditdt)VALUES('litianxiang','litianxiangReply',1,'litianxiang',getdate())";
cmd.ExecuteNonQuery();
{
cmd.CommandText = "INSERT suggestion([Content],Reply,IsAnonymous,Lasteditby,Lasteditdt)VALUES('litianxiang','litianxiangReply',1,'litianxiang',getdate())";
cmd.ExecuteNonQuery();
cmd.CommandText = "UPDATE suggestion SET Content='jiangyingliang' where suggestionid='11'";
cmd.ExecuteNonQuery();
cmd.ExecuteNonQuery();
tran.Commit();
}
catch (Exception ex)
{
tran.Rollback();
this.lbl.Text = ex.Message;
}
finally
{
conn.Close();
}
}
}
catch (Exception ex)
{
tran.Rollback();
this.lbl.Text = ex.Message;
}
finally
{
conn.Close();
}
}