[英]Transaction and multiple queries via ODBC
我有一個接口,通過ODBC連接觸發多個SQL查詢。
這些查詢創建函數,存儲過程,執行存儲過程等。
如果其中一個失敗,我想要一個完整的回滾開始。
這個簡單的計划來查詢begin transaction
和commit transaction
在結束導致運行錯誤后, begin transaction
,因為沒有承諾在這個時候被觸發。
是否有可能在一堆查詢周圍放置一個事務塊?
是的你可以。 我假設您的意思是進行插入或更新各種sql語句(而不是選擇查詢)。 在進行此類操作之前,您應該記住,如果它們與您在查詢之間設置的新數據沒有關系,則只在單個事務中運行查詢。 這是因為新數據尚未提交,因此您無法在下一個語句中使用。
這是一個使用事務運行一組命令的代碼。
/// <summary>
/// Execute commands with an open SQL connection.
/// Note: To execute a stored procedure send to useTransaction parameter false value
/// </summary>
/// <param name="connection">An opened SqlConnection</param>
/// <param name="commands">A string array of the requested commands to execute</param>
/// <param name="useTransaction">true if to force transaction, false to execute the commands without transaction</param>
/// <returns>true for success, otherwise false</returns>
public static bool ExecuteSqlCommands(SqlConnection connection, string[] commands, bool useTransaction)
{
bool bStatus = false;
string[] lines = commands; // regex.Split(sql);
SqlTransaction transaction = null;
if (useTransaction)
transaction = connection.BeginTransaction();
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.Connection = connection;
if (useTransaction)
cmd.Transaction = transaction;
foreach (string line in lines)
{
if (line.Length > 0)
{
cmd.CommandText = line;
cmd.CommandType = CommandType.Text;
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException e)
{
string msg = e.Message;
if (useTransaction)
transaction.Rollback();
throw;
}
}
}
bStatus = true;
}
if (bStatus && useTransaction)
transaction.Commit();
return bStatus;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.