我一直在尝试编写一个以名称作为参数的函数,并检查数据库以查看是否存在具有该名称的表,但由于某种原因,它会一直失败。也许有人可以把我推向正确的方向。感谢!!!
这是我的职能:
int check_table(char tbl_name[])
{
sqlite3 *db;
char *err_msg = 0;
char sql_query[1024];
printf("checking for: %s\n", tbl_name);
int rc = sqlite3_open(db_name, &db);
if (rc != SQLITE_OK)
{
fprintf(stderr, "Cannot open database: %s\n",
sqlite3_errmsg(db));
sqlite3_close(db);
return 1;
}
// assemble string
snprintf(sql_query,sizeof(sql_query), "SELECT name FROM sqlite_master WHERE type='table' AND name=\'%s\'", tbl_name);
rc = sqlite3_exec(db, sql_query, callbackcheck, 0, &err_msg);
if (rc != SQLITE_OK )
{
fprintf(stderr, "Failed to select data\n");
fprintf(stderr, "SQL error: %s\n", err_msg);
sqlite3_free(err_msg);
sqlite3_close(db);
return 1;
}
sqlite3_close(db);
// needs some work here
return 1; // table does exists
//return 0; // table does not exists
}
int callbackcheck(void *NotUsed, int argc, char **argv, char **azColName)
{
NotUsed = 0;
printf("argc: %s - argv: %s - azColName: %s", argc, argv, azColName);
for (int i = 0; i < argc; i++)
{
printf("%s\n", argv[i] ? argv[i] : "NULL");
}
return 0;
}
我的问题在于如何返回True / False,所以理想情况下我会像这样调用函数:bool tb_is_there = check_table(&#34; some_tbl&#34;); 然后我可以返回tb_is_there;
我希望这是有道理的
答案 0 :(得分:0)
如果您想要执行任何操作,但打印出数据,则回调很难使用。在一般情况下,仅使用sqlite3_exec()
的有用方法是将其替换为sqlite3_prepare_v2() / sqlite3_bind_*() / sqlite3_step() / {{3}调用,以便您可以在实际需要处理它的位置读取数据:
sqlite3_stmt *stmt;
const char *sql = "SELECT 1 FROM sqlite_master where type='table' and name=?";
int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
if (rc != SQLITE_OK) {
print("error: ", sqlite3_errmsg(db));
return;
}
sqlite3_bind_text(stmt, 1, tbl_name, -1, SQLITE_TRANSIENT);
rc = sqlite3_step(stmt);
bool found;
if (rc == SQLITE_ROW)
found = true;
else if (rc == SQLITE_DONE)
found = false;
else {
print("error: ", sqlite3_errmsg(db));
sqlite3_finalize(stmt);
return;
}
sqlite3_finalize(stmt);
return found;