sql - c-program sqlite3 检查表是否存在

标签 sql c sqlite

我一直在尝试编写一个将名称作为参数并检查数据库以查看是否存在具有该名称的表的函数,但由于某种原因它一直失败。也许有人可以在这里将我推向正确的方向。谢谢!!!

这是我拥有的功能:

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("some_tbl"); 然后我可以返回 tb_is_there;

我希望这是有道理的

最佳答案

如果您只想打印出数据,则很难使用回调。在一般情况下,唯一使用 sqlite3_exec() 的有用方法是将其替换为 sqlite3_prepare_v2()/sqlite3_bind_*()/sqlite3_step()/sqlite3_finalize()调用,以便您可以在实际需要处理数据的同一位置读取数据:

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;

关于sql - c-program sqlite3 检查表是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49568240/

相关文章:

SQL Server 2012 根据表 2 中的速率更新表速率

c - 如何提高 Haskell 中这种数值计算的性能?

c++ - 如何获取QSqlTableModel中的值?

iphone - sqlite3 在 iPhone 应用程序中插入或替换语法问题

mysql - 从 mysql 中选择多于 1 组的事件?

php - 通过php迁移数据库

c - 在 child 运行时用 fork 做某事

c - 尝试更改内存地址处的值时出现段错误

sqlite - 在MonoTouch中将SQLcipher与sqlite-net一起使用

mysql - Sql 不同的和按 bool 字段分组