gpt4 book ai didi

c++ - 使用 C++ 将数据连接并插入到 MS Access 表中

转载 作者:太空宇宙 更新时间:2023-11-04 12:18:16 35 4
gpt4 key购买 nike

我正在从事一个项目,该项目要求我对 MS Access 表执行插入查询。我一直在网上到处搜索,但似乎没有任何效果。任何帮助将不胜感激。此外,我必须为 VS2008 和 Visual C++ 6.0 编写此代码。谢谢

最佳答案

使用ODBC .连接到数据库并执行 INSERT 查询的示例:

#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;
}

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

关于c++ - 使用 C++ 将数据连接并插入到 MS Access 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6509000/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com