Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect and Insert data into a MS Access table using C++

I am working on a project that requires me to perform insert query on an MS Access table. I have been searching everywhere online but nothing seems to work. Any help would be greatly appreciated. Also, I have to write this for VS2008 and and Visual C++ 6.0. Thanks

like image 932
LaDante Riley Avatar asked Sep 19 '25 18:09

LaDante Riley


1 Answers

Use ODBC. Example of connecting to database and executing INSERT query:

#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <sqlext.h>

WCHAR szDSN[] = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};DSN='';DBQ=C:\\users.mdb";

int _tmain(int argc, _TCHAR* argv[])
{    

HENV    hEnv;
HDBC    hDbc;

/* ODBC API return status */
RETCODE rc;

int     iConnStrLength2Ptr;
WCHAR    szConnStrOut[256];

WCHAR* query = L"INSERT INTO [Users] (name,surname) VALUES ('John','Smith');";

HSTMT           hStmt;

/* Allocate an environment handle */
rc = SQLAllocEnv(&hEnv);
/* Allocate a connection handle */
rc = SQLAllocConnect(hEnv, &hDbc);

/* Connect to the database */
rc = SQLDriverConnect(hDbc, NULL, (WCHAR*)szDSN, 
    SQL_NTS, (WCHAR*)szConnStrOut, 
    255, (SQLSMALLINT*)&iConnStrLength2Ptr, SQL_DRIVER_NOPROMPT);
if (SQL_SUCCEEDED(rc)) 
{

    wprintf(L"Successfully connected to database. Data source name: \n  %s\n", 
        szConnStrOut);  

    /* Prepare SQL query */
    wprintf(L"SQL query:\n  %s\n", query);

    rc = SQLAllocStmt(hDbc,&hStmt);
    rc = SQLPrepare(hStmt, query, SQL_NTS);   

    /* Excecute the query */
    rc = SQLExecute(hStmt); 
    if (SQL_SUCCEEDED(rc)) 
    {
        wprintf(L"SQL Success\n");
    }
    else{
        wprintf(L"SQL Failed\n");
    }
}
else
{
    wprintf(L"Couldn't connect to %s.\n",szDSN);
}

/* Disconnect and free up allocated handles */
SQLDisconnect(hDbc);
SQLFreeHandle(SQL_HANDLE_DBC, hDbc);
SQLFreeHandle(SQL_HANDLE_ENV, hEnv);

getchar();
return 0;
}

Source: https://learn.microsoft.com/en-us/previous-versions/office/developer/office-2007/cc811599(v=office.12)

like image 178
MSDN.WhiteKnight Avatar answered Sep 22 '25 07:09

MSDN.WhiteKnight