How to connect a database and perform CRUD operations in C++?

In order to connect to a database, implement insert, delete, update, and select operations in C++, it is usually necessary to use a database connection library such as ODBC, MySQL Connector/C++, or SQLite C/C++. Below is an example code using ODBC to connect to a database and perform these operations.

#include <iostream>
#include <sql.h>
#include <sqlext.h>

int main() {
    // 初始化ODBC环境
    SQLHENV henv;
    SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &henv);
    SQLSetEnvAttr(henv, SQL_ATTR_ODBC_VERSION, (SQLPOINTER)SQL_OV_ODBC3, 0);

    // 连接数据库
    SQLHDBC hdbc;
    SQLAllocHandle(SQL_HANDLE_DBC, henv, &hdbc);
    SQLConnect(hdbc, (SQLCHAR*)"DSN=YourDSN;UID=YourUID;PWD=YourPWD", SQL_NTS);

    // 执行SQL语句
    SQLHSTMT hstmt;
    SQLAllocHandle(SQL_HANDLE_STMT, hdbc, &hstmt);
    SQLExecDirect(hstmt, (SQLCHAR*)"SELECT * FROM YourTable", SQL_NTS);

    // 处理查询结果
    SQLCHAR buffer[256];
    SQLBindCol(hstmt, 1, SQL_C_CHAR, buffer, sizeof(buffer), NULL);
    while (SQLFetch(hstmt) == SQL_SUCCESS) {
        std::cout << buffer << std::endl;
    }

    // 释放资源
    SQLFreeHandle(SQL_HANDLE_STMT, hstmt);
    SQLDisconnect(hdbc);
    SQLFreeHandle(SQL_HANDLE_DBC, hdbc);
    SQLFreeHandle(SQL_HANDLE_ENV, henv);

    return 0;
}

In this example, we first initialize the ODBC environment, then connect to the database, execute an SQL query, handle the query results, and finally release resources. You can modify the connection string, SQL statement, and result handling approach based on your specific needs. Additionally, you can use other database connection libraries to achieve CRUD operations.

bannerAds