从 SELECT 查询返回多个值

fre*_*owz 2 c# sql

例如,我有一个名为 dbuser 的数据库:

username: teste
password: xxxx
isonline: 1

username: teste2
password: xxxx
isonline: 1
Run Code Online (Sandbox Code Playgroud)

我认为这个查询:

"SELECT username FROM dbuser  WHERE (isonline ='1')"
Run Code Online (Sandbox Code Playgroud)

会同时返回teste和teste2,但是当我在MessageBox中询问结果时,teste和teste2都在线,它只显示teste,但是当我关闭teste连接时,它在MessageBox中出现teste2。我猜它只是将第一行返回给我,那么我如何获得所有值?

这是方法代码:

public static string GetOnline() 
{ 
  string listaOnline; 
  listaOnline = ExecuteQuery("SELECT * username FROM dbuser WHERE (isonline ='1')").ToString();
  return listaOnline;
} 
Run Code Online (Sandbox Code Playgroud)

我把它显示为 MessageBox.Show(DbManager.GetOnline());

Mig*_*gol 5

这应该会以最快的方式为您提供所需的字符串列表。reader.GetString(0)意味着您从索引为 0 的列(因此是第一个)中获取一个刺痛值。

List<string> result = new List<string>();

using (SqlConnection connection = new SqlConnection(databaseConnectionString))
{
  connection.Open();
  using (SqlCommand command = new SqlCommand(query, connection))
  {
    command.CommandType = CommandType.Text;
    using (SqlDataReader reader = command.ExecuteReader())
    {
      while (reader.Read())
      {
        result.Add(reader.GetString(0));
      }

      reader.Close();
    }
    command.Cancel();
  }
}

return result;
Run Code Online (Sandbox Code Playgroud)