Chris
Chris

Reputation: 37

ExecuteReader: Connection property has not been initailized

The error with ExecuteReader: Connection property has not been initialized is giving me a fit. I think I have it set up right. I will show you how I create the mssql connection and then what I am requesting, and the class I created to read/write and open/close the connection. (Three different parts of the app but I just lumped them together so you could see the actual logic flow I hope.)

What am I missing, or where am I supposed to put the connection? Example? I appreciate the help!

Here is the using statement I start with:

using (MSSQL mssqldb = new MSSQL(Constants.msSqlServer, Constants.msSqlDb, Constants.msSqlUid, Constants.msSqlPswd)) 

Here is where I say "Hey, get me my data using my MSSQL class"

using (var results = mssqldb.Read("SELECT TOP 1 * FROM AlertLog ORDER BY AlarmID DESC"))
{
    results.Read();
    legacyAlert = Int32.Parse(results["AlarmId"].ToString().Trim());
}

Here is the MSSQL class

class MSSQL : IDisposable
{
    public MSSQL(string server, string database, string uid, string pswd)
    {
        string msSqlConnectionString = @"Data Source=" + server + ";Initial Catalog=" + database + ";user id=" + uid + ";password=" + pswd;

        SqlConnection msqlConnection = new SqlConnection(msSqlConnectionString);
        msqlConnection.Open();
        Console.WriteLine("MS SQL OPEN!");
    }

    public void Write(string sql)
    {
        using (SqlCommand myCommand = new SqlCommand(sql, msqlConnection))
        myCommand.ExecuteNonQuery();
    }

    public SqlDataReader Read(string sql)
    {
        using (SqlCommand myCommand = new SqlCommand(sql, msqlConnection))
        return myCommand.ExecuteReader();
    }

    public void Dispose()
    {
        try {
            msqlConnection.Close();
        }
        catch (SqlException ex) {
            Console.Error.WriteLine("MS SQL Error - Closing Database");
            Console.Error.WriteLine(ex);
        }
        msqlConnection.Dispose();
    }

    private SqlConnection msqlConnection;
}

Upvotes: 0

Views: 2016

Answers (1)

SLaks
SLaks

Reputation: 888177

msqlConnection is null.

Your constructor creates a local variable named msqlConnection, but does not assign to the field.

Upvotes: 1

Related Questions