Paul
Paul

Reputation: 95

ExecuteReader requires an open connection -- thing it is *already open*, why is this happening?

The code below has been used successfully in other parts of the application without fault.

However, for some reason, an InvalidOperationException is thrown when it comes time to read data from the Access database.

The code below contains only the essentials (not the items that are trying to be read, as that would made readability difficult).

Why am I getting this error, despite the fact I am calling the "Open" method on my connection?

Code follows:

string connString = "Provider= Microsoft.ACE.OLEDB.12.0;" + "Data Source= C:\\temp\\IntelliMed.accdb";
        string queryString = "SELECT patientID, firstName, lastName, patientGender, dateOfBirth, residentialAddress, postalAddress, nationalHealthNumber, telephoneNumber, cellphoneNumber, cscNumber FROM PatientRecord WHERE patientID = @patientID";

        try
        {
            using (OleDbConnection con = new OleDbConnection(connString))
            {
                con.Open();
                OleDbCommand command = new OleDbCommand();
                command.CommandText = queryString;
                command.Parameters.AddWithValue("@patientID", patientID);
                command.Connection = ctnPatientRecord;

                OleDbDataReader prescriptionDetailsReader = command.ExecuteReader();

                while (prescriptionDetailsReader.Read())
                {
                  //Read stuff.
                }
                //Close the reader.
               }
               //Close the connection.
             } //Method "closing" bracket.

Any help is gratefully received. Thanks in advance.

Upvotes: 0

Views: 41

Answers (1)

Stilgar
Stilgar

Reputation: 23571

I think you should associate the command with the connection

command.Connection = con;

or better yet create the command through the connection using the CreateCommand method instead of the constructor.

Upvotes: 1

Related Questions