usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Data;
usingSystem.Data.SqlClient;
usingSystem.Configuration;
namespaceLocal_Transaction
{
publicpartialclassForm1:Form
{
publicForm1()
{
InitializeComponent();
}
privatevoidbtnUpdate_Click(objectsender,EventArgse)
{
using(SqlConnectionconn=newSqlConnection(ConfigurationManager.ConnectionStrings["SqlConn"].ConnectionString))
{
conn.Open();
SqlTransactiontrans=conn.BeginTransaction();
try
{
using(SqlCommandcomm=newSqlCommand())
{
comm.CommandText="InsertIntoStudent(id,Name,Sex,ClassId)Values(@id,@Name,@Sex,@ClassId)";
comm.Connection=conn;
comm.Transaction=trans;
SqlParameter[]paras={newSqlParameter("@id",8)
,newSqlParameter("@Name","wan")
,newSqlParameter("@Sex","M")
,newSqlParameter("@ClassId",1)
};
comm.Parameters.AddRange(paras);
comm.ExecuteNonQuery();
}
using(SqlCommandcomm1=newSqlCommand())
{
comm1.CommandText="UpdateClassSetStudents=Students+1WhereClassid=@Classid";
comm1.Connection=conn;
comm1.Transaction=trans;
comm1.Parameters.Add(newSqlParameter("@Classid",1));
comm1.ExecuteNonQuery();
trans.Commit();
MessageBox.Show("TransactionCommitted!");
}
}
catch(SqlExceptionex)
{
trans.Rollback();
MessageBox.Show("Error-TransactionRolledBack\n"+ex.Message);
}
catch(System.Exceptionex)
{
MessageBox.Show("SystemError\n"+ex.Message);
}
}
}
}
}
|
|