thlgood
thlgood

Reputation: 1295

Create SQLite3 tables with C, but got an empty database file

This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>

#define DBFILE "./userinfo.db" //It's empty file

int main(int argc, char *argv[])
{
    int retval;
    sqlite3_stmt *stmt;
    sqlite3 *handle;

    retval = sqlite3_open(DBFILE, &handle);
    if(retval)
    {
        perror("sqlite3_open");
        exit(-1);
    }
    printf("Connection successful...\n");
    char create_table[] = "CREATE TABLE IF NOT EXISTS"
    "users(uname TEXT PRIMARY KEY, pass TEXT NOT NULL)";

    retval = sqlite3_exec(handle, create_table, 0, 0, 0);
    if (retval)
    {
        perror("sqlite3_exec");
        exit(-1);
    }
    sqlite3_close(handle);
    return 0;
}

I compiled it and run it without any errors.

Before I run it, the database file userinfo.db is an empty file

after I run it, I got a empty database file again.

Why? table didn't be saved?

Upvotes: 1

Views: 814

Answers (1)

CL.
CL.

Reputation: 180270

I get:

$ testprogram
Connection successful...
sqlite3_exec: No such file or directory

or, when the file already exists:

$ testprogram
Connection successful...
sqlite3_exec: Success

The reason is that the sqlite3_* functions do not set errno, which is the error code output by perror.

To output SQLite error messages, use sqlite3_errmsg:

fprintf(stderr, "sqlite3_exec: %s\n", sqlite3_errmsg(handle));

With that, I get:

$ testprogram
Connection successful...
sqlite3_exec: near "EXISTSusers": syntax error

Upvotes: 2

Related Questions