cdub
cdub

Reputation: 25701

Connection not initialized

I have a quick issue with my connection not being intialized.

When I call the create method, I pass in a bunch of varnames, say "ABC,XYZ, etc".

On the first pass of the foreach, the stored procedure gets called correctly and things work fine. But on the second pass, I get a "Connectionstring property has not been intialized.

Should I mover the myConn.open and myConn.close outside of the loop?

My code:

public bool Create()
{
        bool isSuccess = true;

        ConnectionStringSettings myConnectionStringSetting = ConfigurationManager.ConnectionStrings[0];
        DbProviderFactory dbFactory = DbProviderFactories.GetFactory(myConnectionStringSetting.ProviderName);

        DbConnection myConn = dbFactory.CreateConnection();
        myConn.ConnectionString = myConnectionStringSetting.ConnectionString;

        DataTable myDataTable = new DataTable();

        string[] varNamesArray = m_variableNames.Split(',');

        foreach (string varName in varNamesArray)
        {
            string vn = varName.Trim();

            //stored procedure

            DbCommand myCommand = dbFactory.CreateCommand();
            myCommand.CommandText = "s_LockVariables";
            myCommand.CommandType = CommandType.StoredProcedure;
            myCommand.Connection = myConn;

            //variables            

            DbParameter param1 = myCommand.CreateParameter();
            param1.ParameterName = "@varName";
            param1.DbType = DbType.String;
            param1.Value = vn;
            myCommand.Parameters.Add(param1);

            DbParameter param2 = myCommand.CreateParameter();
            param2.ParameterName = "@datasetID";
            param2.DbType = DbType.Int32;
            param2.Value = m_datasetID;
            myCommand.Parameters.Add(param2);

            DbParameter param3 = myCommand.CreateParameter();
            param3.ParameterName = "@userID";
            param3.DbType = DbType.Int32;
            param3.Value = m_userID;
            myCommand.Parameters.Add(param3);

            DbParameter param4 = myCommand.CreateParameter();
            param4.ParameterName = "@currentTime";
            param4.DbType = DbType.DateTime;
            param4.Value = DateTime.Now;
            myCommand.Parameters.Add(param4);

            try
            {
                using (myConn)
                {
                    myConn.Open();
                    myCommand.ExecuteNonQuery();
                    myConn.Close();
                }
            }
            catch (Exception e)
            {
                isSuccess = false;
                throw new Exception(e.Message);
                //TODO:  catch data error

                return isSuccess;
            }
        }

        return isSuccess;
    }

Upvotes: 0

Views: 510

Answers (2)

Steve
Steve

Reputation: 216273

This code

using (myConn) 
{ 
    myConn.Open(); 
    myCommand.ExecuteNonQuery(); 
    myConn.Close(); 
} 

destroys the myConn var at the end of the first loop
I will try to change it in this way

    using(DbConnection myConn = dbFactory.CreateConnection())
    {
        myConn.ConnectionString = myConnectionStringSetting.ConnectionString;   
        DataTable myDataTable = new DataTable();   
        string[] varNamesArray = m_variableNames.Split(',');   
        foreach (string varName in varNamesArray)   
        {   
            ... 
            // the rest of your code
            ...
            // Then do not add the using statement here 
            myConn.Open(); 
            myCommand.ExecuteNonQuery(); 
            myConn.Close(); 
            ....
        }
    } 

also, I will change the try/catch part of your code.
If you really need to return from this code with a boolean then

catch (Exception e)       
{       
    isSuccess = false;       
    // If you rethrow a new Exception here you will never reach the return statement
    // In this cases (assuming we are inside a library) I will try to save the exception
    // in a global var (GetLastError comes to mind) or log everything in a file
    return isSuccess;       
}       

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500015

You're disposing of myConn within the foreach loop here:

using (myConn)
{
    myConn.Open();
    myCommand.ExecuteNonQuery();
    myConn.Close();
}

I suggest you just change that to declare the variable right there:

using (DbConnection myConn = dbFactory.CreateConnection())
{
    myConn.ConnectionString = myConnectionStringSetting.ConnectionString;
    myConn.Open();
    myCommand.Connection = myConn;
    myCommand.ExecuteNonQuery();
    // Closed automatically due to being disposed
}

Or just have a single using statement outside the loop - you might as well use the same connection for all the commands, right?

Upvotes: 6

Related Questions