MST

星途 面试题库

面试题:C++ RAII在数据库连接中的基本实现

请简述如何使用C++的RAII机制来管理数据库连接,假设使用的是MySQL数据库,给出简单的代码框架,包含连接的建立和释放。
46.8万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试
  1. RAII机制简介
    • RAII(Resource Acquisition Is Initialization)即资源获取即初始化。在C++中,通过将资源的获取(如打开文件、分配内存、建立数据库连接等)放在对象的构造函数中,将资源的释放(如关闭文件、释放内存、关闭数据库连接等)放在对象的析构函数中。当对象生命周期结束时,析构函数会自动调用,从而保证资源被正确释放。
  2. 使用RAII管理MySQL数据库连接的代码框架
#include <mysql/mysql.h>
#include <iostream>

class MySQLConnection {
public:
    MySQLConnection(const char* host, const char* user, const char* passwd, const char* db, unsigned int port) {
        connection = mysql_init(nullptr);
        if (connection == nullptr) {
            std::cerr << "mysql_init() failed" << std::endl;
            return;
        }
        if (mysql_real_connect(connection, host, user, passwd, db, port, nullptr, 0) == nullptr) {
            std::cerr << "mysql_real_connect() failed" << std::endl;
            mysql_close(connection);
            connection = nullptr;
        }
    }

    ~MySQLConnection() {
        if (connection != nullptr) {
            mysql_close(connection);
        }
    }

    MYSQL* getConnection() {
        return connection;
    }

private:
    MYSQL* connection;
};

可以这样使用这个类:

int main() {
    MySQLConnection conn("localhost", "root", "password", "test_db", 3306);
    if (conn.getConnection() != nullptr) {
        // 在这里可以执行SQL语句等操作
        MYSQL* mysql = conn.getConnection();
        if (mysql_query(mysql, "SELECT * FROM some_table")) {
            std::cerr << "Query failed: " << mysql_error(mysql) << std::endl;
        } else {
            MYSQL_RES* result = mysql_store_result(mysql);
            // 处理查询结果
            mysql_free_result(result);
        }
    }
    return 0;
}

在上述代码中:

  • MySQLConnection类的构造函数负责建立MySQL数据库连接。如果连接建立失败,会进行相应的错误处理。
  • MySQLConnection类的析构函数负责关闭数据库连接,保证在对象销毁时连接被正确释放。
  • getConnection方法用于获取MYSQL指针,以便在外部执行SQL语句等数据库操作。在main函数中,展示了如何创建MySQLConnection对象并使用其获取的连接执行简单的SQL查询操作。