pi-2r
pi-2r

Reputation: 1279

c# sql and loop while

I try to read all the fields of a column (second column -link-) in my database. I find this example, but I can't manage to read one column of varchar type:

SQLConnection.Open();

using (SqlCommand command = new SqlCommand("SELECT link  FROM shop", SQLConnection))
using (SqlDataReader reader = command.ExecuteReader())
{
    while (reader.Read())
    {
        Console.WriteLine("{2}",reader.GetString(2));
    }
}

I've got this error:

Index was outside the bounds of the array.

and I don't understand why...

Thanks in advance :)

Upvotes: 1

Views: 2885

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460128

Replace

Console.WriteLine("{2}",reader.GetString(2));

with

Console.WriteLine("{0}",reader.GetString(0));

since 1.)the composite formatting feature uses zero-based indexed placeholders and 2.) you are selecting just one field from the table, so the only index is 0.

Upvotes: 2

Related Questions