这两天写程序用到了transaction。本来想在SQL-Server中的存储过程中写,发现直接在C#程序中写也很方便,于是在C#中完成了。现在把两种transaction的方式写出来。
在C#中:红色字体是使用transaction的关键部分
Common comm = new Common();
Session["lunwbh"] = Convert.ToInt32(GridView1.DataKeys[GridView1.SelectedIndex]["论文编号"]);
SqlConnection conn = new SqlConnection(comm.getsqlconnection());
conn.Open();
SqlCommand command = new SqlCommand("Pro_BianJ_LunW",conn);
command.CommandType = CommandType.StoredProcedure;
SqlParameter parm1 = command.Parameters.Add("@LunWBH", SqlDbType.Int, 4);
parm1.Direction = ParameterDirection.Input;
parm1.Value = Convert.ToInt32(Session["lunwbh"]);
SqlParameter parm2 = command.Parameters.Add("@BianJM", SqlDbType.VarChar, 20);
parm2.Direction = ParameterDirection.Input;
parm2.Value = Convert.ToString(Session["ZhuCYHM"]);
SqlTransaction trans;
trans = conn.BeginTransaction();
command.Transaction = trans;
try
{
command.ExecuteNonQuery();
trans.Commit();
Response.Write("<script>alert('已经把这篇论文放到您的论文库中!')</script>");
}
catch
{
trans.Rollback();
Response.Write("<script>alert('保存失败!')</script>");
}
finally
{
conn.Close();
}
在存储过程中的transaction:(摘自MSDN)
DECLARE @TranName VARCHAR(20);
SELECT @TranName = 'MyTransaction';
BEGIN TRANSACTION @TranName;
USE AdventureWorks;
DELETE FROM AdventureWorks.HumanResources.JobCandidate
WHERE JobCandidateID = 13;
COMMIT TRANSACTION @TranName;
GO