如何在sql表中查找str

How to find str in sql table

本文关键字:查找 str sql      更新时间:2023-10-16

代码只需要让调用者知道path是否在表中。下面的c++代码使用select count(*)sqlite3_get_table正确地做到了这一点,但只做了很短的一段时间,然后就死了。sqlite3_get_table显然存在问题。这里有一个非常相似的问题,但我不知道如何将这个答案应用于我的问题。我已经阅读了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);
}