我正在尝试实现一个方法,该方法将采用给定的连接字符串并返回一个包含 SQL 视图内容的 ArrayList。
我已经验证了连接字符串和视图本身的有效性。但是我看不到下面的代码中的问题所在。在调试中,当它运行 ExecuteReader 方法然后尝试进入 while 循环以遍历视图中的记录时,它会立即退出,因为由于某种原因sqlReader.Read()没有。
public ArrayList GetEligibles(string sConnectionString)
{
string sSQLCommand = "SELECT field1, field2 FROM ViewEligible";
ArrayList alEligible = new ArrayList();
using (SqlConnection sConn = new SqlConnection(sConnectionString))
{
// Open connection.
sConn.Open();
// Define the command.
SqlCommand sCmd = new SqlCommand(sSQLCommand, sConn);
// Execute the reader.
SqlDataReader sqlReader = sCmd.ExecuteReader(CommandBehavior.CloseConnection);
// Loop through data reader to add items to the array.
while (sqlReader.Read())
{
EligibleClass Person = new EligibleClass();
Person.field1 = sqlReader["field1"].ToString();
Person.field2 = sqlReader["field2"].ToString();
alEligible.Add(Person);
}
// Call Close when done reading.
sqlReader.Close();
}
return alEligible;
}
注意,EligibleClass只是代表视图结果的一行的类对象。