freedowz
freedowz

Reputation: 92

Return multiple values from a SELECT query

For example i have a database called dbuser:

username: teste
password: xxxx
isonline: 1

username: teste2
password: xxxx
isonline: 1

I thought that this query:

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

would return both teste and teste2, but when i ask the result for example in a MessageBox, with both teste and teste2 online, it only shows teste, but when i close the teste connection then it appears teste2 in the MessageBox. Im guessing its only returning the first row to me, so how can i get all the values?

This is the method code:

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

and I show it as MessageBox.Show(DbManager.GetOnline());

Upvotes: 2

Views: 17519

Answers (3)

SST
SST

Reputation: 459

You can do something like this, it is just outline of the code, will give you some hint(need to add some spaces/ special characters to between names).

string user = string.Empty;
foreach (var item in DbManager.GetOnline())
{
    user += item;
}
MessageBox.Show(user);

Hope it will help..

Also you can do it in the following way:

List<string> listUser= new List<string>();
listUser =DbManager.GetOnline();
string users= string.Join(",", listUser.ToArray());
 MessageBox.Show(users);

In this way Username will be printed separated by ",".

Upvotes: -1

BLoB
BLoB

Reputation: 9725

Try something like the following, create a class for users:

[Table(Name = "foo")]
public class Users
{
   [Column(Name = "user_name")]
   username {get; set;};

   [Column(Name = "user_pword")]
   password {get; set;};

   [Column(Name = "user_isonline")]
   isonline {get; set;};
}


public static List<Users> GetOnline() 
{ 
   List<Users> listaOnline = new List<Users>(); 
   listaOnline = ExecuteQuery("SELECT * username FROM dbuser WHERE (isonline ='1')");
   return listaOnline;
} 

Upvotes: 0

Migol
Migol

Reputation: 8448

This should give you a list of strings that you want in the fastest manner. reader.GetString(0) means that you take a sting value from column with index 0 (so the first one).

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;

Upvotes: 6

Related Questions