用C++编写查找数据库text.accdb文件中“食堂窗口”表中平均受欢迎程度为10的菜品名称
时间: 2023-12-06 16:40:59 浏览: 30
要使用C++编写程序连接Access数据库,可以使用ODBC(Open Database Connectivity)API。以下是示例代码:
```c++
#include <windows.h>
#include <sql.h>
#include <sqlext.h>
#include <iostream>
using namespace std;
int main()
{
// Initialize variables
SQLHANDLE sqlenvhandle;
SQLHANDLE sqlconnectionhandle;
SQLHANDLE sqlstatementhandle;
SQLRETURN retcode;
// Allocate an environment handle
retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &sqlenvhandle);
// Set the ODBC version to use
retcode = SQLSetEnvAttr(sqlenvhandle, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);
// Allocate a connection handle
retcode = SQLAllocHandle(SQL_HANDLE_DBC, sqlenvhandle, &sqlconnectionhandle);
// Connect to the database
retcode = SQLConnect(sqlconnectionhandle, (SQLCHAR*)"YOUR_DSN_NAME", SQL_NTS, (SQLCHAR*)"YOUR_USERNAME", SQL_NTS, (SQLCHAR*)"YOUR_PASSWORD", SQL_NTS);
// Allocate a statement handle
retcode = SQLAllocHandle(SQL_HANDLE_STMT, sqlconnectionhandle, &sqlstatementhandle);
// Execute the query
retcode = SQLExecDirect(sqlstatementhandle, (SQLCHAR*)"SELECT 菜品名称 FROM 食堂窗口 WHERE 平均受欢迎程度 = 10", SQL_NTS);
// Fetch the results
SQLCHAR name[256];
SQLLEN name_length;
while(SQLFetch(sqlstatementhandle) == SQL_SUCCESS)
{
SQLGetData(sqlstatementhandle, 1, SQL_C_CHAR, name, 256, &name_length);
cout << name << endl;
}
// Free the statement handle
retcode = SQLFreeHandle(SQL_HANDLE_STMT, sqlstatementhandle);
// Disconnect from the database
retcode = SQLDisconnect(sqlconnectionhandle);
// Free the connection handle
retcode = SQLFreeHandle(SQL_HANDLE_DBC, sqlconnectionhandle);
// Free the environment handle
retcode = SQLFreeHandle(SQL_HANDLE_ENV, sqlenvhandle);
return 0;
}
```
在上面的代码中,需要将"YOUR_DSN_NAME"替换成你的ODBC数据源名称,"YOUR_USERNAME"和"YOUR_PASSWORD"替换成你的数据库用户名和密码。注意,需要安装Access数据库驱动程序才能使用ODBC API访问Access数据库。