-1
public string getString()
{

  con.ConnectionString = ConnString;
  con.Open();
  string sp = "select top 3 hotelid from hotel order by NEWID()";
  SqlCommand cmd = new SqlCommand(sp, con);

  SqlDataAdapter sa = new SqlDataAdapter(cmd);
  cmd.ExecuteNonQuery();
  reader = cmd.ExecuteReader();
  while (reader.Read()) //Call Read to move to next record returned by SQL //OR call --While(reader.Read()) 
  {
    det  = reader[0].ToString();

  }
  reader.Close();
  con.Close();
  return det;
}

当我执行此代码时,我只能检索一项数据?但是当我执行 SQL 查询时,我能够随机检索 3 项数据。

4

1 回答 1

1

您正在覆盖每个循环det上的变量。while

您要么需要创建一个集合并添加到其中,要么连接字符串(注意+=)...

det += reader[0].ToString();

更新

如上所述,另一种选择是创建一个集合,例如...

public List<string> getString()
{
  ...
  List<string> ret = new List<string>;
  while (reader.Read())
    ret.Add(reader[0].ToString());
  ...
  return ret;
}
于 2012-07-12T14:45:23.137 回答