i am using the OleDbDataReader to read a column from an Access database and i want to be able to use the same reader to read the column again in the same function because i am doing some comparison between 2 databases and some times the identical records in the databases are not in the same order so i've to loop through the database until i find the specified record then compare.

questions are

is there a function to get the current row index of an OleDbDataReader?

and how do i reset the OleDbDataReader to the first row?

有帮助吗?

解决方案

You can't reset the reader to the start because it is designed for forward-only reading.

There are a couple of other ways to approach this kind of problem:

  1. If the set of data you are comparing is reasonably sized and you are comparing on one field, you could cache the data from one database in a keyed object, such as a generic dictionary. Then, as you are reading data from the second database, you could fetch the details from the dictionary based on the key and perform the comparison that way.

  2. You could issue standalone queries for each record in one database to see if there is a match in the second database rather than having nested readers.

其他提示

According to the MSDN, the OleDbDataReader class

Provides a way of reading a forward-only stream of data rows from a data source.

That means that there is no way to go back to a previous row. All you can do is read the current row or move to the next one. If you need to be able to randomly access any row, the typical solution is to load all the rows into a list, such as a DataTable and then process the rows in the list.

I'm solving a similar problem, and using a DataTable was the easiest way around he forward-only issue with the data readers.

            DataTable table = new DataTable("DataTable");
            for (int colNum = 0; colNum < reader.FieldCount; colNum++)
            {
                DataColumn col = new DataColumn();
                col.ColumnName = reader.GetName(colNum);
                table.Columns.Add(col);
            }//colNum
            while (reader.Read())
            {
                DataRow row = table.NewRow();
                for (int colNum = 0; colNum < reader.FieldCount; colNum++)
                {
                    string columnName = reader.GetName(colNum);
                    row[columnName] = reader.GetValue(colNum);
                }//for
                table.Rows.Add(row);
            }//while
            table.AcceptChanges();

Carlos A Merighe.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top