1

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?

3
  • char create_table[] = "CREATE TABLE IF NOT EXISTS" "users(uname TEXT PRIMARY KEY, pass TEXT NOT NULL)"; shouldn't this be just one string? Commented Oct 17, 2012 at 1:39
  • 2
    You need a space between EXISTS and users, but no clue why there's no error. Commented Oct 17, 2012 at 1:44
  • 1
    @IonutHulub Two string literals with only whitespace between them gets automatically concatenated as a single string literal. Commented Oct 17, 2012 at 7:02

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.