Search code examples
ms-accesssqldatatypestype-conversionjetoledbdatareader

To which C# data type does MS Access "Number" type correspond?


According to http://msdn.microsoft.com/en-us/library/office/aa211091(v=office.11).aspx, the MS Jet database engine has no "NUMBER" data type; yet that is what I see in the MS Access design view of the table that I'm querying - that the

data type of the first column I'm retrieving wit the query is of the "NUMBER" data type.

I've got this code that breaks, both when I try to convert that value to Int32 and to Double:

// A set comprised of two columns are returned from a query in cmd
using (OleDbDataReader oleDbD8aReader = cmd.ExecuteReader())
{
    while (oleDbD8aReader != null && oleDbD8aReader.Read())
    {
        //var accountID = oleDbD8aReader.GetString(0); // <-- this fails (it's a number, not a string)
        //var accountID = oleDbD8aReader.GetInt32(0);   // <-- this also fails!
        var accountID = oleDbD8aReader.GetDouble(0); // <-- as does this!
        var deptName = oleDbD8aReader.GetString(1);    
        . . .
    }
}

Why does it fail to convert to string, int, or double? What should I convert it to instead?


Solution

  • 'Number' in the Access table designer is a collection of data types, not a specific type itself - you need to look at the field properties below the field list to see what the actual type is.

    Alternatively, you could look the field type up programmatically. Using Delphi and DAO the code would look like this:

    uses
      DAO_TLB; //may need importing first via Component|Import Component
    
    procedure Foo;
    var
      Engine: DBEngine;
      DB: Database;
      Table: TableDef;
    begin
      Engine := CoDBEngine.Create;
      DB := Engine.OpenDatabase('C:\Somewhere\Database.mdb',
        {exclusively?}False, {read-only?}True, '');
      Table := DB.TableDefs['MyTableName'];
      case Table.Fields['MyFieldName'].Type_ of
        dbBoolean: ;
        dbByte: ;
        dbInteger: ;
        dbLong: ;
        dbCurrency: ;
        dbSingle: ;
        dbDouble: ;
        dbDate: ;
        dbBinary: ;
        dbText: ;
        dbLongBinary: ;
        dbMemo: ;
        dbGUID: ;
        dbBigInt: ;
        dbVarBinary: ;
        dbChar: ;
        dbNumeric: ;
        dbDecimal: ;
        dbFloat: ;
        dbTime: ;
        dbTimeStamp: ;
      end;
    end;
    

    I would assume the C#/ADO.NET equivalent would be similar-ish.