Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select * only return one value

I want select multiple (all) values from table Account.

string query = "SELECT * FROM Account";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand command = new SqlCommand(query, connection);
        SqlDataReader reader;
        connection.Open();
        reader = command.ExecuteReader();
        reader.Read();
        label1.Text = reader["PasswordHash"].ToString();
        connection.Close();

Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3 it still returns only one value. Table have more than one value i checked form Management Studio, there query run as they should.

Thanks in advance.

like image 849
Dejan Stuparic Avatar asked Dec 01 '22 07:12

Dejan Stuparic


2 Answers

Because you are not looping through the query results, it shows up only one result.

string query = "SELECT * FROM Account";
    SqlConnection connection = new SqlConnection(connectionString);
    SqlCommand command = new SqlCommand(query, connection);
    SqlDataReader reader;
    connection.Open();
    reader = command.ExecuteReader();
    While(reader.Read())
{
    label1.Text += " " +reader["PasswordHash"].ToString();
}
    connection.Close();

The above code loops through the query results and will give you what you want in a concatenated string assigned to label1.text. You can also view the results by inserting Console.WriteLine(reader["PasswordHash"].ToString()); in the while loop

like image 150
reggie Avatar answered Dec 04 '22 09:12

reggie


You should do

while (reader.Read())
    // process information

You need to iterate all the information you retrieved.

Sidenote: Use using statements on your SqlConnection, SqlCommand, and SqlDataReader to make sure the objects get disposed correctly.

like image 45
Jesus Ramos Avatar answered Dec 04 '22 07:12

Jesus Ramos