Using Access database from Visual C++

Tweet


There are many ways to access to Microsoft Access database file (.mdb) from Visual C++. One example is follows.


Source code

#include "stdafx.h"
#include <atldbcli.h>
#include <locale.h>

int _tmain(int argc, _TCHAR* argv[])
{
    _tsetlocale(LC_ALL, _T(
"Japanese"));
    CoInitialize(NULL);

    CDataSource ds;
    CSession ss;
    CCommand<CDynamicAccessor> rs;
    DBTYPE dbt;
    
int i;

    
if(ds.OpenFromInitializationString(_T("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Testdata.mdb"))) {
        printf(
"CDataSource Error\n");
        
return 1;
    }
    
if(ss.Open(ds)) {
        printf(
"CSession Error\n");
        
return 1;
    }
    
if(rs.Open(ss, _T("SELECT * FROM Table1"))) {
        printf(
"CCommand Error\n");
        
return 1;
    }
    
for(i = 1; i <= (int)rs.GetColumnCount(); i++) {
        rs.GetColumnType(i, &dbt);
        printf(
"Column number = %d, Column name = %S, Column type = %d\n", i, rs.GetColumnName(i), dbt);
    }
    
while(!rs.MoveNext()) {
        printf(
"%S, %S\n", rs.GetValue(2), rs.GetValue(3));
    }
    rs.Close();
    ss.Close();
    ds.Close();

    CoUninitialize();
    
return 0;
}


Database example

ID Title Genre
Number Text Text
1 Wuv U CANDY RAVE
2 SigSig MAKINA
3 I'm so Happy HAPPY HARDCORE

Output

Column number = 1, Column name = ID, Column type = 3
Column number = 2, Column name = Title, Column type = 130
Column number = 3, Column name = Genre, Column type = 130
Wuv U, CANDY RAVE
SigSig, MAKINA
I'm so Happy, HAPPY HARDCORE


Back