简体   繁体   中英

OleDB only returning DbNull, what have I done wrong?

I've got the following code:

// personCount = 7291; correct value
int personCount = (int)new OleDbCommand("SELECT COUNT(*) AS [count] FROM [Individual]", _access).ExecuteScalar();
List<Person> people = new List<Person>();

OleDbCommand personQuery = new OleDbCommand("SELECT * FROM [Individual]", _access);

using (OleDbDataReader personReader = personQuery.ExecuteReader())
{
    int curPerson;

    while (personReader.Read())
    {
        curPerson++;
        // This runs several times
        if (personReader.IsDBNull(0)) continue;
        // [snip] create a new Person and add it to people
    }
    // at this point, curPerson == 7291 but the list is empty.
}

This is my exact code. Field 0 is the primary key, so should never be null, but every single row being returned from the database has all the fields set to DBNull! I can't see what I'm doing wrong, can anyone shed some light on this?

My connection string is:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\path\\to\\database.mdb

For one reason or another, using the * column selector was jumbling columns. Using a specific list fixes this. I'm still curious as to reasons why this might happen.

Fixed version:

OleDbCommand personQuery = new OleDbCommand("SELECT [ID], [Surname], ... FROM [Individual]", _access);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM