C++ mysql准备好的语句close和unique_ptr

标签 c++ mysql pointers unique-ptr

我有 2 个与 C++ 和 mysql 连接器相关的问题。

  1. 如果我使用sql::PreparedStatement作为unique_ptr,是否需要调用prepareStatement的close()方法,还是在删除unique_ptr时自动调用它?我还需要关闭 sql::resultSet 吗?

  2. 是否需要调用unique_ptr的reset()方法来删除该指针?

我有这个函数,它从PreparedStatement接收unique_ptr,执行查询并返回结果。

    std::unique_ptr<sql::ResultSet> CommonService::select(std::unique_ptr<sql::PreparedStatement> &pstmt) {
std::unique_ptr<sql::ResultSet> resulSet = nullptr;
    try {
        resulSet = std::unique_ptr<sql::ResultSet>(pstmt->executeQuery());
        pstmt->close(); // i need to do this? or is closed when unique_ptr is deleted?
       // pstmt.reset(); i need to do this? or is deleted automatically
    } catch (sql::SQLException &e) {
        std::cout << "# ERR: SQLException in " << __FILE__;
        std::cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << std::endl;
        std::cout << "# ERR: " << e.what();
        std::cout << " (MySQL error code: " << e.getErrorCode();
        std::cout << ", SQLState: " << e.getSQLState() << " )" << std::endl;
        pstmt->close(); // i need to do this? or is closed when unique_ptr is deleted?
    }

    return resulSet;
}

谢谢

最佳答案

If I use sql::PreparedStatement as unique_ptr, do I need to call the close() method of prepareStatement or is it called automatically when unique_ptr is deleted? Do I also need to close the sql::resultSet?

不,您不需要调用 close() 方法。像这样只初始化一次查询语句。一旦超出范围,查询语句将被自动销毁。处理数据库异常而不关闭语句。

就您的 resultSet 而言,您可以将其声明为局部变量,如下所示

// global scope
std::unique_ptr<sql::Connection> sqlConnection;
std::unique_ptr<sql::Statement> stmt;

void InitializeDatabase() { // call once
   sqlConnection.reset(sqlDriver->connect(host, user, pwd));
   stmt.reset(sqlConnection->createStatement());
}

void getData(/* */)
{    
    std::unique_ptr<sql::ResultSet> res(stmt->executeQuery(/**/));    
    do {
        while (res->next()) {  // extract data from statement
            /* */
        }
    } while (stmt->getMoreResults());  
} // res will be automatically destroyed here.

Do you need to call the reset () method of unique_ptr to remove that pointer?

不,unique_ptr 对象一旦超出范围就会自动销毁。

关于C++ mysql准备好的语句close和unique_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57335127/

相关文章:

c++ - 我的代码似乎什么都不做

mysql - OpenShift、JBoss EAP 6 - 如何重新添加 MySQL 驱动程序

php - 有效地复制/复制/备份数据库表 - mysql

c++ - 声明指针;星号位于类型和名称之间的空格左侧还是右侧?

用 c 中的数组构造我自己的 strcat 函数

我可以在需要 int* 的地方传递 NULL 吗?

c++ - 为什么找不到这个 std::map 键?

c++ - 将 C++ 对象(尤其是 STL 容器)移动到特定的内存位置

c++ - C++ 中的通知中心

mysql - psql表查询