Visual Studio uses C++ language to connect to Access

C++ connects to Access database:


For example: To connect to the Access database, you need to use the ODBC (Open Database Connectivity) API in C++. The following are the steps to connect to an Access database:


1.Install ODBC driver

First you need to install the ODBC driver for Access on your computer. These drivers can be downloaded from the official Microsoft website.


2. Create ODBC data source

Find "ODBC Data Source" or "ODBC Data Source (32-bit)" in the control panel, then create a new data source and select "Microsoft Access Driver (*.mdb, .accdb)" or "Microsoft Access Driver" as the type Program (.mdb)". Follow the prompts to set the database path and related information.


3. Include header files

In the C++ code, the header files "sql.h", "sqlext.h" and "odbcinst.h" need to be included.


4. Define connection handles and status variables

You need to define a connection handle and a state variable to store connection status and related information.

SQLHANDLE henv;  // 环境句柄
SQLHANDLE hdbc;  // 连接句柄
SQLRETURN retcode;  // 状态变量


5. Initialize the ODBC environment

Use the SQLAllocHandle function to initialize the ODBC environment handle.

retcode = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
retcode = SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_UINTEGER);


6. Connect to the database

Use the SQLAllocHandle function to allocate a connection handle, and then use the SQLConnect function to connect to the database.

retcode = SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
retcode = SQLConnect(hdbc, (SQLCHAR*)"ODBC数据源名称", SQL_NTS, (SQLCHAR*)"用户名", SQL_NTS, (SQLCHAR*)"密码", SQL_NTS);


7. Execute SQL statements

After the connection is successful, you can use the SQLExecDirect function to execute SQL statements.

SQLCHAR* sql = (SQLCHAR*)"SELECT * FROM 表名";
SQLExecDirect(hstmt, sql, SQL_NTS);


8. Disconnect

Use the SQLDisconnect and SQLFreeHandle functions to disconnect and release related resources.

SQLDisconnect(hdbc);
SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
SQLFreeHandle(SQL_HANDLE_ENV, henv);


Summarize:

The above are the basic steps for connecting to the Access database. The specific implementation can be adjusted and optimized according to the actual situation.

提示:项目已打包,有需要的可在资料库下载

Guess you like

Origin blog.csdn.net/huzhuohuan/article/details/130496491