SQLite3:数据库是空的吗?

时间:2014-05-07 18:20:08

标签: c sqlite

我正在尝试使用sqlite3在我的C程序上创建一个带有表的数据库,但是数据库总是被创建为空,尽管它是使用sqlite shell创建的非空的,  这是我的代码:

int main(void)
{
    printf("hello\n");
    sqlite3 *sqdb;
    sqlite3_initialize();
    const char* db = "test";
    sqlite3_open(db, &sqdb);
    const char* stmt = "CREATE TABLE IF NOT EXISTS testtable(creationdate DATE, data VARCHAR);";
    sqlite3_stmt *ppstmt;
    if (sqlite3_prepare_v2(sqdb, stmt, -1, &ppstmt, 0)!=SQLITE_OK)printf("error!\n");
    sqlite3_finalize(ppstmt);
    getch();
    return 0;
}

请帮我解决问题。

2 个答案:

答案 0 :(得分:3)

sqlite3_prepare_v2()只编译SQL但不运行它。在编译语句上调用sqlite3_step()来运行它,或者使用将prepare + step + finalize组合成一个函数调用的sqlite3_exec()

答案 1 :(得分:1)

试试这个:

   int main(void)
{
    printf("hello\n");
    sqlite3 *sqdb;
    int ret;
    sqlite3_initialize();
    const char* db = "test.sqlite3";
    sqlite3_open(db, &sqdb);
    const char* stmt = "CREATE TABLE IF NOT EXISTS testtable(creationdate DATE, data VARCHAR);";
    sqlite3_stmt *ppstmt=NULL;

    ret=sqlite3_exec(sqdb,stmt,0,0,0);
    if(ret!=SQLITE_OK)printf("error!\n");
    else printf("Table added\n");
    sqlite3_finalize(ppstmt);
    sqlite3_close(sqdb);
    return 0;
}

请务必记住在操作后关闭数据库。