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

标签 c++ sqlite embedded-linux

代码只需要让调用者知道 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/

相关文章:

c++ - std::thread 的段错误

mysql - 如何从 C++/WinRT UWP 应用连接到 SQL Server?

c++ - 带有移动物体的 gluLookAt 和 glFrustum

c++ - 使特定于 Unix 的 CMake 过程跨平台

android - 如何判断android rawQuery更新成功?

android - 将 SQLite 数据库从 Android 复制到 PC(然后再复制回来)?

linux - 不可读/可写分区 Linux

Linux CONFIG_LOCALVERSION_AUTO : What specific folders/files must be in the source tree for this feature to function?

c++ - 如何在 BeagleBoard 上的 Angstrom Linux 上启动时运行 C++、PortAudio 应用程序?

c++ - 使用 Sqlite3 和 C++ 以编程方式执行 VACUUM 命令?