事務可控制和維護事務中每個操作的一致性和完整性。具體說明可參考其它文章。
這裡主要是說明在C#中執行事務的使用方法。其代碼如下:
/// <summary>
/// 執行事務
/// </summary>
/// <param name="sSqlList">一次執行的多條語句列表</param>
public void RunOldDbTransaction(string[] sSqlList)
{
sConnectionString = ConfigurationManager.AppSettings.Get("UserConnection");
OracleConnection ocConnection = new OracleConnection(sConnectionString);
ocConnection.Open();
//建立並開啟事務
OracleTransaction oraTrans = ocConnection.BeginTransaction(IsolationLevel.ReadCommitted);
OracleCommand ocCommand = ocConnection.CreateCommand();
ocCommand.Transaction = oraTrans;
try
{
//迴圈事務中語句
foreach (string sVal in sSqlList)
{
ocCommand.CommandText = sVal;
ocCommand.ExecuteNonQuery();
}
//完成後確認事務
oraTrans.Commit();
}
catch (Exception ex)
{
//出錯後復原事務
oraTrans.Rollback();
throw ex;
}
finally
{
ocConnection.Close();
}
}
註:SQL中用法BEGIN TRANS
DECLARE @orderDetailsError int, @productError int
//執行的語句1
DELETE FROM Order Details WHERE ID=111
//得到錯誤
SELECT @orderDetailsError = @@ERROR
//執行的語句2
DELETE FROM Products WHERE ProductID=112
//得到另外一個錯誤
SELECT @productError = @@ERROR
IF @orderDetailsError = 0 AND @productError = 0
COMMIT TRANS
ELSE
ROLLBACK TRANS
這種方法可以查閱相關sql server 協助。