我在問自己是否有可能檢查ADO.NET中是否可以回滾當前事務。ADO.NET檢查是否可能回滾
在MSDN提出以下建議執行:
private static void ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
// Start a local transaction.
transaction = connection.BeginTransaction("SampleTransaction");
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
command.ExecuteNonQuery();
command.CommandText =
"Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
command.ExecuteNonQuery();
// Attempt to commit the transaction.
transaction.Commit();
Console.WriteLine("Both records are written to database.");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
此外,還有注:回滾當一個事務 的try/catch異常處理應始終使用。如果連接終止或者事務已在服務器上回滾,則回滾會生成InvalidOperationException。
但我不能真正相信try/catch是推薦的解決方案來檢查回滾是否可能。
我知道在SQL Server實現中,如果事務是「殭屍」,則SQLTransaction對象在Connection屬性上返回null。
但是,這是相當具體的實現,它只適用於SQL Server。
那麼,是否有一個數據庫獨立的方式來檢測事務是否可以回滾?
TIA 馬丁