gpt4 book ai didi

c++ - 如何在sql表中查找str

转载 作者:行者123 更新时间:2023-11-28 07:46:14 25 4
gpt4 key购买 nike

代码只需要让调用者知道 path 是否在表中。下面的 c++ 代码使用 select count(*)sqlite3_get_table 正确执行此操作,但只持续了一小会儿,然后就死了。sqlite3_get_table 显然存在问题。有一个非常相似的问题here但我不知道如何将此答案应用于我的问题。我已经阅读了 sqlite 文档并阅读了 sqlite 教程。我已经使用 sqlite3_exec 来初始化数据库并插入新记录,但同样,看不到如何编写一个健壮的 c++ 方法,如果它在表中找到或没有找到匹配项,它只返回一个 bool 值。正如我所说,下面的代码有效,但调用次数不超过几百次。这不应该是处理数据库最简单的事情之一吗?是否有关于如何执行此操作的任何简单示例或关于解决此问题的最佳方法的建议?

bool ifFound(string path) {
if (turn_off) return false;
char **result;
int nrow = 0; // Number of result rows
int ncol = 0; // Number of result columns
char * zErrMsg = 0; // Error message
if (SQLITE_OK != sqlite3_open(database_path.c_str(), &db)) {
coutError(__FILE__, __LINE__, "Can't open database " + database_path);
return false;
}
int count = 0;
string sqlCommand = "select count(*) from my_table where path='"+path+"'";
if (SQLITE_OK ==
sqlite3_get_table(db, sqlCommand.c_str(),&result,&nrow,&ncol,&zErrMsg))
count = atoi(result[ncol]);
else coutError(__FILE__, __LINE__, sqlCommand + " " + zErrMsg);
sqlite3_free_table(result);
sqlite3_close(db);
return (count != 0);
}

最佳答案

摆脱 sqlite3_get_table 的一种方法是将其替换为 sqlite3_exec,一个处理查询结果的回调,以及一个保存计数的全局变量。

static int pathFound = 0;
int sqlCallback(void *p, int argc, char **argv, char **azColName) {
pathFound = atoi(argv[0]);
return 0;
}
void checkPath(string path) {
string sqlCommand = "select count(*) from m_table where path='"+path+"'";
rc = sqlite3_exec(db, sqlCommand.c_str(), sqlCallback, 0, &zErrMsg);
if (SQLITE_OK != rc) {
coutError(__FILE__, __LINE__, sqlCommand + "\n" + zErrMsg);
sqlite3_free(zErrMsg);
}
sqlite3_close(db);
if (0 == pathFound) doInsert(path);
}

关于c++ - 如何在sql表中查找str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14836309/

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