mardi 11 août 2015

How do you properly check an SQLiteDataReader for null values?

I am trying to read some rows from a table in an SQLite database. I have a try/catch around my reader code:

try {
            using (SQLiteConnection dbCon = new SQLiteConnection("Data Source=" + dbPath)) {
                dbCon.Open();
                using (SQLiteCommand command = new SQLiteCommand(sqlcmd, dbCon)) {
                    using (SQLiteDataReader rdr = command.ExecuteReader()) {
                        while (rdr.Read()) {
}
catch(exception ex) { throw ex; }

Something like that.

My problem is that any way that I check the reader values, say like:

if (rdr[3].ToString() != "" && rdr[3] != null) {}

It will always pass that if and then still throw an exception of "The given key was not present in the dictionary."

I simply want to reliably check these values so that I can skip over one but without having to hit the catch every time.

Given the previous example of checking for null:

if (rdr[3].ToString() != "" || rdr[3] != null) {
int something = Convert.ToInt32(rdr[3]);
}

this will error everytime there is no value in that field, because it will also always pass the 2 checks in the if.

Aucun commentaire:

Enregistrer un commentaire