user2124495
user2124495

Reputation: 59

Using Retrieved Data from a Parameterized SQL Query

If I'm using a parameterized query (ASP.NET with C#) in SQL, such as

var db = Database.Open("Database1");
SqlCommand cmd = new SqlCommand("SELECT * FROM pageinfo WHERE pageID = @pageID");
cmd.Parameters.AddWithValue("@pageID", 1);

And later on in the page, I want to do a foreach loop of whatever data was retrieved:

foreach(var row in ???)

What would I use (in place of the ???) to access the data I just retrieved?

Thanks.

Upvotes: 1

Views: 83

Answers (2)

Tigran
Tigran

Reputation: 62276

It depends on how you execute a query.

Usually it's done by SqlCommand.ExecuteReader

For example, in your case, you can:

.... 

 SqlDataReader reader = cmd .ExecuteReader();
 while (reader.Read())
 {
   ...
 }

But there are also other ways to rertieve the data, for example using DataSet For a complete example on how to do that can have a look on:

Using ADO.NET for beginners

Upvotes: 3

Soner Gönül
Soner Gönül

Reputation: 98810

You can use while iteration statement with SqlCommand.ExecuteReader instead of foreach. Take a look this;

var db = Database.Open("Database1");
SqlCommand cmd = new SqlCommand("SELECT * FROM pageinfo WHERE pageID = @pageID");
cmd.Parameters.AddWithValue("@pageID", 1);
SqlDataReader reader = cmd.ExecuteReader();

while (reader.Read())
{
    Console.WriteLine(reader[0]);
}

reader[0] returns first row of first column and reader[1] returns first row of second column if your data has of course.

Upvotes: 0

Related Questions