The C# using statement, SQL, and SqlConnection

前端 未结 5 1106
刺人心
刺人心 2020-12-01 18:53

Is this possible using a using statement C# SQL?

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnectio         


        
5条回答
  •  我在风中等你
    2020-12-01 19:37

    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
            }
        }
    }
    

提交回复
热议问题