Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The C# using statement, SQL, and SqlConnection

Is this possible using a using statement 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();
    }
}

What if there’s a error while opening the connection?

The using statement is try and finally
No catch

So if I catch outside the using brackets will the catch catch the connection opening error?

If not, how to implement this with using the using statement a shown above?

like image 920
user287745 Avatar asked Jun 20 '10 11:06

user287745


4 Answers

It's possible to do so in C# (I also see that code is exactly shown in MSDN http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx). However, if you need to be defensive and for example log potential exceptions which would help troubleshooting in a production environment, you can take this approach:

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
        }
    }
}
like image 109
Kevin Le - Khnle Avatar answered Sep 22 '22 15:09

Kevin Le - Khnle


If you want to catch any error then you'll need to wrap everything in try - catch block. using blocks simply ensure that non-managed resources are disposed, they cannot handle exceptions.

Also,SqlCommand implements IDisposable, so I'd suggest putting that in a using block as well.

like image 40
David Neale Avatar answered Sep 25 '22 15:09

David Neale


Just write it out explicitely:

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();
}
like image 43
Willem van Rumpt Avatar answered Sep 25 '22 15:09

Willem van Rumpt


Yes, you can put the using block in a try block, and the following catch will catch any errors related to the try block.

like image 27
Femaref Avatar answered Sep 23 '22 15:09

Femaref