问题
how do i retrieve data from a table within a loop or something. That means I want to retrieve row by row at a time. but the sequence of rows may differ. For example, 1st time i want 5rd row,then 2nd, then 9...so on.
I searched it through the internet. I got only two answers.
Use several SqlConnection objects.
reader= sqlCommand.ExecuteReader(); While(reader.Read()){ reader["Column Name"].ToString(); }
If you got my problem, please help me Thank you.
回答1:
Sounds like you should correct your data layer to return the values in the order you are going to process them. It would be easiest and fastest! :)
As an alternative I'd suggest that you load your result into a DataTable:
DataTable table = new DataTable();
using ( SqlCommand command = new SqlCommand() )
{
// TODO: Set up your command here
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
adapter.Fill(table);
}
}
// Use your DataTable like this...
if ( table.Rows.Count >= 5 ) {
DataRow firstRow = table.Rows[0]; // #1 row
DataRow fifthRow = table.Rows[4]; // #5 row
DataRow secondRow = table.Rows[1]; // #2 row
}
/Alex
回答2:
It's probably best to read your data into a DataSet, as shown in this example:
http://quickstart.developerfusion.co.uk/quickstart/howto/doc/adoplus/GetDataFromDB.aspx
回答3:
The reader approach is usually the way to go, but your query (or SP) must already select the data in the order you want to retrieve it.
Alternatively you can load everything into a DataSet and do random access on the rows in it.
回答4:
Two ways, that I see:
1) Get all rows in one sql statement, then access the row you need in memory.
Or (of "everything" is too much or you need recent data)
2) Get only the specific row you need, and again for the next row.
回答5:
What exactly are you trying to achieve? Retrieve random rows from a DS or do you have certain criteria for selecting which rows you want returned? And if so couldn't you order them before loading them into the reader?
来源:https://stackoverflow.com/questions/4490441/sql-data-retrieve-c-sharp