Skip to main content
 首页 » 编程设计

c#之从 SELECT 查询返回多个值

2024年02月20日10bluestorm

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

username: teste 
password: xxxx 
isonline: 1 
 
username: teste2 
password: xxxx 
isonline: 1 

我认为这个查询:

"SELECT username FROM dbuser  WHERE (isonline ='1')" 

会同时返回 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; 
}  

我将其显示为 MessageBox.Show(DbManager.GetOnline());

请您参考如下方法:

这应该以最快的方式为您提供所需的字符串列表。 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;