我想讀取查詢返回的XML,我測試了查詢,並且它返回的XML與正確的項目..但後面的代碼有一個problem..It正確讀取的第一個項目,但隨後拋出異常..我不知道什麼是錯的(唯一的例外發生在嘗試去while循環的第二次。請參見下面的代碼數據讀取返回(讀者關閉時無效嘗試讀取)
// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
SqlCommand myCommand = new SqlCommand("GetItemsXML", myConnection);
// Mark the Command as a SP
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SP
SqlParameter parameterPortalID = new SqlParameter("@TheID", SqlDbType.Int, 4);
parameterPortalID.Value = portalID;
myCommand.Parameters.Add(parameterPortalID);
SqlParameter parameterKeywords = new SqlParameter("@myWords", SqlDbType.VarChar, 4000);
parameterKeywords.Value = myWords;
myCommand.Parameters.Add(parameterWords);
// Execute the command
myConnection.Open();
SqlDataReader reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
string xmlOut = "";
while (reader.Read()) //SECOND ITERATION THROWS (Invalid attempt to read
// when reader is closed)
{
xmlOut = xmlOut + reader[0].ToString();
}
xmlOut = "<MyItemsList>" + xmlOut + "</ZMyItemsList>";
reader.Close();
myConnection.Close();
return xmlOut;
}
不相關,但您確實應該在'using'語句中使用'SqlConnection'和'SqlCommand'聲明,以確保正確處置。 – Oded