locked
ExecuteScalar: Connection property has not been initialized RRS feed

  • Question

  • I am pretty much a junior in programming.  But I must say that I really don't see what is wrong with this one.  Maybe I look at my code to closly!!  Can somebody help me please?? 

    public class SybaseDataAccessObject : IDisposable        {

                    // Class Variable Definition 
            private DbProviderFactory m_factory;
            private DbConnection m_connection;
            public int counts = 0;

            public SybaseDataAccessObject(String Server, String Db, String Host, String Pwd)
                    {
                            //Connection Definition
                m_factory = DbProviderFactories.GetFactory("System.Data.Odbc");
                var m_connection = m_factory.CreateConnection();

                m_connection.ConnectionString = String.Format("DBASE={0};DSN={1};UID={2};PWD={3}", Server, Db, Host, Pwd);

                try
                {
                    m_connection.Open();
                }
                catch (DbException e)
                {
                    Console.WriteLine("{0} Exception caught.", e);
                }
                    }


            public int GetCount(string schema, string whereClause)
            {
                    var command = m_factory.CreateCommand();
                    command.Connection = m_connection;
     
                  command.CommandText = String.Format("SELECT COUNT(*) FROM {0}.GEODA KEY JOIN {0}.HH01 WHERE {1}", schema, whereClause);
                    counts = (int)command.ExecuteScalar(); //where error occure
                    return counts;
           }


           #region IDisposable Members

            public void Dispose()
            {
                if (m_connection != null && m_connection.State != ConnectionState.Closed)
                {
                   m_connection.Close();
                   m_connection.Dispose();
                }
            }

            #endregion
        }
    }

     

    ERROR: 

    System.InvalidOperationException was unhandled
    Message="ExecuteScalar: Connection property has not been initialized."
    Source="System.Data"


    M. Chalut
    Wednesday, June 2, 2010 3:18 PM

Answers

  • In your SybaseDataAccessObject() constructor you are creating a new m_connection object. This only has scope in this constructor and the m_Connection outside this constructor remains uninitialised.

    Remove var from the second line in the SybaseDataAccessObject() constructor to initialise the connection object you declared at class level.

    • Edited by kevinjp Wednesday, June 2, 2010 3:27 PM rename method to constructor
    • Marked as answer by Harry Zhu Monday, June 7, 2010 7:10 AM
    • Unmarked as answer by Mylen33 Wednesday, June 9, 2010 6:24 PM
    • Marked as answer by Mylen33 Wednesday, June 9, 2010 6:47 PM
    Wednesday, June 2, 2010 3:26 PM