星期二, 8月 31, 2010

ASP.NET Using Transaction

最近越來越常用到同時要更新多個Table的功能,本來想偷懶的用SqlDataSource來解決就好了,
可是隨著SQL語法的越來越複雜,已經不能這樣做了,而SqlDataSource預設也不支援Transaction的功能,在網路上找了很多個SqlDataSource結合Transaction的用法,結果沒有一個真的可以用的,真是奇怪,只好乖乖的回來使用SqlConnection來做了,而為了預防SQL injection,我又特別喜歡用傳參數的方式來,結果我的程式就變的行數特別多了!

string strSQL = @"INSERT INTO [drug_list] ([Center], [RandomNo], [DrugCode], [IsUsed], [IsDrugActive], [DrugExpiredDate], [CheckInDate], [IsDrugExpired], [UpdateUser], [UpdateTime]) VALUES(@Center, @RandomNo, @DrugCode, @IsUsed, @IsDrugActive, @DrugExpiredDate, @CheckInDate, @IsDrugExpired, @UpdateUser, GETDATE());
DECLARE @ID int;
SELECT @ID=[idx] FROM [drug_list] WHERE [Center]=@Center AND [RandomNo]=@RandomNo;
INSERT INTO [drug_List_AT] ([idx],[Center], [RandomNo], [DrugCode], [IsUsed], [IsDrugActive], [DrugExpiredDate], [CheckInDate], [IsDrugExpired], [UpdateUser], [UpdateTime]) VALUES(@ID, @Center, @RandomNo, @DrugCode, @IsUsed, @IsDrugActive, @DrugExpiredDate, @CheckInDate, @IsDrugExpired, @UpdateUser, GETDATE());";
SqlConnection connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
connection.Open();
SqlTransaction sqlTx = connection.BeginTransaction();
SqlCommand command = new SqlCommand(strSQL, connection);
command.Transaction = sqlTx;
try
{
command.Parameters.Add("Center", Request.QueryString["Site"].ToString());
command.Parameters.Add("RandomNo", this.txtRandomNo.Text);
command.Parameters.Add("DrugCode", this.txtPackageNo.Text);
command.Parameters.Add("IsUsed", "0");
command.Parameters.Add("IsDrugActive", "0");
command.Parameters.Add("DrugExpiredDate", this.txtExpiredDate.Text);
command.Parameters.Add("IsDrugExpired", "0");
command.Parameters.Add("UpdateUser", Session["UserID"].ToString());
command.Parameters.Add("CheckInDate", this.txtCheckInDate.Text);
command.ExecuteNonQuery();
sqlTx.Commit();
Response.Write("Save Successfully.");
}
catch
{
sqlTx.Rollback();
Response.Write("Save Failed");
}
finally
{
connection.Close();
connection.Dispose();
sqlTx.Dispose();
command.Dispose();
}

放個範例在這邊,預防我忘記了還可以快點找到參考的

沒有留言: