下面的代碼已經在應用程序的其他部分成功使用,沒有錯誤。ExecuteReader需要一個打開的連接 - 它已經打開*,爲什麼會發生這種情況?
但是,由於某種原因,從Access數據庫讀取數據時,會引發InvalidOperationException。
下面的代碼只包含要領(不是試圖閱讀的項目,因爲這會使可讀性變得困難)。
爲什麼我得到這個錯誤,儘管我在我的連接上調用「打開」方法?
代碼如下:
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.
任何幫助感激地接受。提前致謝。
您在調用con.Open()之後將命令的連接設置爲新值。這個連接是否也打開? – Dirk 2014-08-31 08:16:57
嗯。我不確定,現在你提到它。我會在那個問題上回復你。 – Paul 2014-08-31 08:19:57