gpt4 book ai didi

c++ - MySQL 结果集包含 1 行,但调用 getstring 导致访问冲突

转载 作者:行者123 更新时间:2023-11-29 20:12:00 25 4
gpt4 key购买 nike

我目前正在学习 C++,并正在慢慢取得进展,但遇到了 MySQL 选择和准备语句的问题。

我有一个链接到库的应用程序,该应用程序正在调用库函数,如下所示:

try
{
DynamicConfig dynamicConfig;
string value = "";
dynamicConfig.getValueFromDBConfig("Test Group", "TestName", &value);
stringstream logStream;
logStream << "Dynamic Config Value: " << value;
bitsLibrary.writeToLog(logStream.str());
}
catch (sql::SQLException ex)
{
cout << "SQL Exception: " << ex.what() << endl;
}
catch (exception ex)
{
cout << "General Exception: " << ex.what() << endl;
}

在 DynamicConfig 类的库中,我有 getValueFromDBConfig 方法,其中包含以下内容:

bool DynamicConfig::getValueFromDBConfig(string groupName, string sectionName, string *value)
{
//Connection *conn = NULL;
PreparedStatement *statement = NULL;
ResultSet *resultset = NULL;
try
{
DBManager dbManager;
Connection *conn = dbManager.getDriverConnection();
statement = conn->prepareStatement("SELECT * FROM config_items, config_groups WHERE config_groups.Name=? AND config_items.Name=? AND config_groups.id = config_items.ConfigGroupID");
statement->setString(1, groupName.c_str());
statement->setString(2, sectionName.c_str());
resultset = statement->executeQuery();
cout << "Found " << resultset->rowsCount() << " rows" << endl;
if (resultset->rowsCount() > 0)
{

while (resultset->next())
{
cout << "Value: " << resultset->getString("Value") << endl;
*value = resultset->getString("Value");
}
delete conn;
delete statement;
delete resultset;
return true;
}
else
{
bitsLibrary.writeToLog("No rows were returned", "DynamicConfig", "getValueFromDBConfig");
}
}
catch (SQLException ex)
{
stringstream logStream;
logStream << "Failed to get DB config value. SQL Exception: " << ex.what();
bitsLibrary.writeToLog(logStream.str(), "DynamicConfig", "getValueFromDBConfig");
throw ex;
}
catch (exception ex)
{
stringstream logStream;
logStream << "Failed to get DB config value. General Exception: " << ex.what();
bitsLibrary.writeToLog(logStream.str(), "DynamicConfig", "getValueFromDBConfig");
throw ex;
}
return false;
}

它似乎成功执行了查询,因为它将 1 rows 打印到控制台,但是,当我调用 resultset->getstring("Value") 时,它会抛出错误:

Exception thrown at 0x00007FFF7E831EBA (msvcp140d.dll) in TestApp.exe 0xC0000005. Access violation reading location 0xFFFFFFFFF.

我不明白为什么这不起作用,它有一行,而且我正在查看的数据库表肯定有名为 Value 的列。

最佳答案

最后终于明白了。我需要按如下方式运行 getstring

*value = resultset->getString("Value").c_str()

我不明白为什么我需要这样做,我使用的MySQL示例代码来自 https://dev.mysql.com/doc/connector-cpp/en/connector-cpp-examples-results.html没有显示这一点,所以如果有人可以阐明这一点,那就太好了。

关于c++ - MySQL 结果集包含 1 行,但调用 getstring 导致访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40030027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com