11

これは、usingステートメントC#SQLを使用して可能ですか?

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}

接続を開くときにエラーが発生した場合はどうなりますか?

usingステートメントはtryであり、最後に
キャッチなしです。

それで、使用ブラケットの外側をキャッチすると、キャッチは接続開放エラーをキャッチしますか?

usingそうでない場合は、上記のステートメントを使用してこれを実装する方法は?

4

5 に答える 5

18

C#でこれを行うことは可能です(コードがMSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspxに正確に示されていることもわかります)。ただし、防御する必要があり、たとえば、実稼働環境でのトラブルシューティングに役立つ可能性のある例外をログに記録する必要がある場合は、次のアプローチを取ることができます。

private static void CreateCommand(string queryString,
string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
           connectionString))
    {
        try
        {
            SqlCommand command = new SqlCommand(queryString, connection);
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
        catch (InvalidOperationException)
        {
            //log and/or rethrow or ignore
        }
        catch (SqlException)
        {
            //log and/or rethrow or ignore
        }
        catch (ArgumentException)
        {
            //log and/or rethrow or ignore
        }
    }
}
于 2010-06-20T12:02:53.680 に答える
5

エラーをキャッチしたい場合は、すべてを--blockでラップする必要がありtryますcatchusingブロックは、管理されていないリソースが破棄されることを保証するだけであり、例外を処理することはできません。

また、をSqlCommand実装しているので、それもブロックIDisposableに入れることをお勧めします。using

于 2010-06-20T11:48:19.313 に答える
2

明示的に書き出すだけです。

SqlConnection connection = new SqlConnection(connectionString);
try
{
    using (SqlCommand command = new SqlCommand(queryString, connection))
    {
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}
catch (Exception e)
{
    // ...handle, rethrow. Also, you might want to catch
    // more specific exceptions...
}
finally
{
    connection.Close();
}
于 2010-06-20T11:49:30.307 に答える
1

usingはい、ブロックをブロックに入れることができます。try以下catchは、ブロックに関連するエラーをキャッチしtryます。

于 2010-06-20T11:48:46.440 に答える