Connect and Insert data into a MS Access table usi

2019-08-01 09:07发布

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

2条回答
我命由我不由天
2楼-- · 2019-08-01 09:41

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://docs.microsoft.com/en-us/previous-versions/office/developer/office-2007/cc811599(v=office.12)

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-01 09:48

You have (far too) many choices: ADO/RDO, DAO, ODBC, and OLE DB, to name only a few. DAO is officially deprecated. ADO/RDO aren't officially, but MS doesn't seem to care much about them anymore either. With VC 6, however, obsolescent is pretty much a fact of life. I believe they're all still supported to at least some degree under VS 2008, but they no longer, for example, include any wizards to help with using DAO.

That basically leaves OLE DB and ODBC as your first couple of choices. MS is still actively supporting and developing them, and the others are unlikely to provide any major advantage anyway.

I should add that VC++ 6.0 provides quite a few features missing from VS2008 for writing applications that use databases. You might want to look at what I showed in a previous question for some guidance.

查看更多
登录 后发表回答