0

我目前正在处理一项任务,试图从 SQL Server 数据库中获取值并将它们存储在一个数组中。我的连接很好,但是我无法将返回的值放入数组中。

这是我所拥有的,自从我问这个问题以来已经改变了一点:

public int Bay;
int temp;

[DataContract]
public Garage()
{
    List<Garage> Bays = new List<Garage>();

    SqlConnection connection = new SqlConnection("Data   Source=fastapps04.qut.edu.au;Initial Catalog=*******;User ID=******;Password=******");
    connection.Open();

    SqlCommand command = new SqlCommand("SELECT Bay FROM Garage", connection);

    SqlDataReader reader = command.ExecuteReader();

    while (reader.Read())
    {
        temp = reader.GetOrdinal("Bay");
        Bays.Add(temp);
    }

    Bays.ToArray();

    reader.Close();
    connection.Close();
}

得到错误

Bays.Add(temp)
4

3 回答 3

0

每次调用reader.Read()都会将读者推进到结果集的下一行。您似乎已经假设您可以通过一次读取将所有行都放入您的数组中。

如果您更改代码以便temp在循环的每次迭代中添加到数组中,while您应该会发现它有效。

我会输入代码,但我在手机上。:)

于 2014-10-25T07:27:54.237 回答
0

将 Bays 更改为 a List<int>,并返回列表或调用.ToArray()列表。此外,使用Using带有连接和命令的语句。

   List<int> Bays = new List<int>(); 

   using(SqlConnection connection = new SqlConnection("connString"))
    {
        connection.Open();

        using (SqlCommand command = new SqlCommand("SELECT Bay FROM Garage", 
                                                                       connection))
        {
            using (SqlDataReader reader= command.ExecuteReader())
            {
                while (reader.Read()) 
                {
                    Bays.Add(reader.GetInt32(reader.GetOrdinal("Bay")));
                }         
            }
        } 
     }
     ..... 
于 2014-10-25T08:22:40.280 回答
-1

只需对代码进行少量修改即可获得所需的结果。

 public Garage()
{

    SqlConnection connection = new SqlConnection("Data   Source=fastapps04.qut.edu.au;Initial Catalog=*******;User ID=******;Password=******");
    connection.Open();

    SqlCommand command = new SqlCommand("SELECT Bay FROM Garage", connection);

    SqlDataReader reader = command.ExecuteReader();
    List<Garage> listBays =new List<Garage>();
    while (reader.Read())
    {
        temp = reader.GetInt32(reader.GetOrdinal("Bay"));
        listBays.Add(temp);
    }
    Garage[] Bays=listBays.ToArray();
    reader.Close();
    connection.Close();

}
于 2014-10-25T08:00:42.193 回答