我有 2 个与 C++ 和 mysql 连接器相关的问题。
如果我使用sql::PreparedStatement作为unique_ptr,是否需要调用prepareStatement的close()方法,还是在删除unique_ptr时自动调用它?我还需要关闭 sql::resultSet 吗?
是否需要调用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/