是否需要在 C# 中使用带有 using 关键字的 sqltransaction

问题描述

我有以下两个使用块:

using (sqlConnection connection = new sqlConnection(_connectionString))
{
    String query = "query...";
    using (sqlCommand command = new sqlCommand(query,connection))
    {
        command.Parameters.AddWithValue("@param","paramValue");

        connection.open();
        int result = command.ExecuteNonQuery();

        // Check Error
        if (result < 0)
            Console.WriteLine("Error inserting data into Database!");
    }
}

是否足以使此查询安全,还是需要像 this post 中那样声明交易?

解决方法

您要求安全,这可能与资源的观点或数据库数据的观点相关。

using 语句

using statement 是释放非托管资源的 try-catch-finally 语句的语法糖。

请注意,这与您的数据库代码无关,它仅处理 IDisposable 对象,在您的代码中为 SQLConnectionSQLCommand

您可以选择不编写 using 语句,但它非常有用,我建议您使用 using 语句...不仅适用于数据库连接,还适用于其他非托管资源。

SQLTransaction

如果有多个操作,并且您关心确保它们以原子方式运行(全部完成或没有任何更改),则需要一个数据库事务。

您可以直接在 your SQL code 中进行数据库事务,也可以使用 SQLTransaction 在您的 .net 代码中声明:

在您的 SQL 代码中:

BEGIN TRANS myTrans
Insert into Region (RegionID,RegionDescription) VALUES (100,'Description');
Insert into Region (RegionID,RegionDescription) VALUES (101,'Description');
COMMIT TRANS myTrans

或在 .NET 中声明:

try
{
    command.CommandText = "Insert into Region (RegionID,'Description')";
    command.ExecuteNonQuery();
    command.CommandText = "Insert into Region (RegionID,'Description')";
    command.ExecuteNonQuery();

    // Attempt to commit the transaction.
    transaction.Commit();
    Console.WriteLine("Both records are written to database.");
}
,

单个操作不需要事务,因为单个操作会创建隐式事务。当您处理多个应该被视为“原子”的操作时,事务是有意义的,即如果一个操作失败,您可以回滚所有更改(事务还有一些用途,但我尽量保持简单)