如何在sql表中查找str
How to find str in sql table
代码只需要让调用者知道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);
}
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最接近的大于当前数字的数字的索引
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 查找后更改类变量
- 使用正则表达式regex_search在字符串中查找字符串
- 使用gcc从静态链接的文件中查找可选符号
- 在C++中查找范围的长度
- 算法问题:查找从堆栈中弹出的所有序列
- 在Windows中查找扬声器输出的当前音量级别
- 如何在C++中使用X509证书模在令牌中查找私钥
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 在 for 循环中查找问题时遇到困难
- Python str to C++ to Python str
- C :查找(str,ind)返回几个-1
- 在字符串中查找确切的子str
- 如何在sql表中查找str