c++ - 如何多次使用mysql_fetch_row而不获取NULL值(C++)(MySQL C API)
问题描述
我正在制作一个 RPG 项目/魔法管理器,如果该人选择了一个不存在的数字,我正在尝试处理这种情况,但是 mysql_fetch_row 在第二次运行时一直返回 NULL。
我想我需要res = mysql_store_result(conn);
再次运行,但如果我尝试在第二个时间段内运行它,它会给我这个错误:
An exception was thrown at 0x00007FF82E124216 (libmysql.dll) (in rpg.exe): 0xC0000005: An access violation occurred while reading location 0x0000000000000010
这是我当前的代码:
void listarPersonagem(MYSQL* conn) {
MYSQL_ROW row;
MYSQL_RES* res;
std::string query = "SELECT * FROM personagem";
const char* q = query.c_str();
qstate = mysql_query(conn, q);
int escolha = -1;
std::map<int, int> indexMap;
if(!qstate) {
res = mysql_store_result(conn);
signed int fields = static_cast<int>(mysql_num_rows(res));
while(escolha < 0 || escolha > fields) {
system("cls");
std::cout << "\t\t\t\t Personagens\n" << std::endl;
indexMap = {};
int i = 1;
while(row = mysql_fetch_row(res)) { //It returns NULL and doesn't run
std::cout << i << " - " << row[1] << std::endl;
indexMap.insert({i, std::atoi(row[0])});
i++;
}
std::cout << "0 - Voltar" << std::endl;
std::cout << "\n\n=>";
std::cin >> escolha;
}
}
int id = escolha != 0 ? indexMap[escolha] : 0;
row = NULL;
res = nullptr;
qstate = NULL;
}
可能有用的信息:
IDE:Visual Studio 2019
操作系统:Windows 10
解决方案
我想出了如何“重新运行”mysql_fetch_row。我所做的只是将 更改while
为 anif
以检查用户输入的值并将此函数类型更改为int
,这样我就可以知道发生了什么并知道是否需要再次运行它。
int listarPersonagem(MYSQL* conn) {
MYSQL_ROW row;
MYSQL_RES* res;
std::string query = "SELECT * FROM personagem";
const char* q = query.c_str();
qstate = mysql_query(conn, q);
int escolha = -1;
std::map<int, int> indexMap;
if(!qstate) {
res = mysql_store_result(conn);
system("cls");
std::cout << "\t\t\t\t Personagens\n" << std::endl;
indexMap = {};
int i = 1;
while(row = mysql_fetch_row(res)) {
std::cout << i << " - " << row[1] << std::endl;
indexMap.insert({i, std::atoi(row[0])});
i++;
}
std::cout << "0 - Voltar" << std::endl;
std::cout << "\n\n=>";
std::cin >> escolha;
signed int fields = static_cast<int>(mysql_num_rows(res));
if(escolha < 0 || escolha > fields) {
return -1; // if the number doesn't exist, it will return -1
}
}
int id = escolha != 0 ? indexMap[escolha] : 0;
row = NULL;
res = nullptr;
qstate = NULL;
return 0;
}
switch(escolha) {
// sair
case 0:
return 0;
// ver personagens
case 1:
escolha = listarPersonagem(conn) == 0 ? -1 : 1; // if the function returns -1, it will be runned again
break;
推荐阅读
- java - eventsource-android 从 Flux 服务器端点返回空数据字符串
- python - 列出从 mongoengine 对象创建的字典中的键
- go - golang 运算符 % 未在 float64 上定义
- regex - 用于替换字符的正则表达式模式
- docker - Kubernetes/Rancher 中的 Docker 网络
- javascript - 在 Android 中构建 URL 时如何隐藏查询参数?
- hadoop - Analysing log files using Pig
- sql - 比较 2 个不同来源之间的数据
- c++ - OpenGL 显示一个正方形而不是一个立方体
- python - 如何在 android 的 Chaquopy python 中导入 numpy