[dba-VB] C# - what am I doing wrong here?

jwcolby jwcolby at colbyconsulting.com
Fri Jul 23 14:05:14 CDT 2010


OK so I want to do the right thing, I just don't know how.

8(

In the following code, I want to declare the connection and command object outside the try, 
initialize the two objects inside of a try, catch any errors, and finally cleanup.  The objects in 
the finally say that they were never initialized.  If I put them inside of the try, it complains 
that the objects aren't valid in the scope of the finally.  If I initialize them outside of the try 
it isn't using a try and errors will not be handled.

It seems that I am damned any way I look at this.

namespace projBaseObjects
{
     class clsSQLReadWrite
     {
         public static void ExecuteNonQuery(string strCnn, string strSQL)
         {
             SqlConnection mCnn;
             SqlCommand myCommand;
             try
             {
                 mCnn = new SqlConnection(strCnn);
                 mCnn.Open();
                 myCommand = new SqlCommand(strSQL, mCnn);
                 myCommand.ExecuteNonQuery();
             }
             catch (SqlException)
             {
                 throw;
             }
             catch (Exception)
             {
                 throw;
             }
             finally
             {
                 myCommand.Dispose();
                 mCnn.Close();
             }
         }
     }
}

-- 
John W. Colby
www.ColbyConsulting.com



More information about the dba-VB mailing list