0

My code is very simple, just create a empty table. This is my code:

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

int main(int argc, char *argv[])
{
    sqlite3 *ppdb;
    int retval;

    retval = sqlite3_open_v2("v2.db", &ppdb, 
                        SQLITE_OPEN_CREATE, "unix-none");
    if (retval != SQLITE_OK)
    {
        printf(stderr, "%s\n", sqlite3_errmsg(ppdb));
        return 1;
    }
    retval = sqlite3_exec(ppdb, 
             "CREATE TABLE IF NOT EXISTS userinfo \
             (id TEXT PRIMARY KEY, pass TEXT NOT NULL)",
             NULL, NULL, NULL);
    if (retval != SQLITE_OK)
    {
        fprintf(stderr, "%s\n", sqlite3_errmsg(ppdb));
        return 1;
    }
    sqlite3_close(ppdb);
    return 0;
}

But when I run it, I got this error message:

Out of memory

I debug this code, I found sqlite3_open_v2 has returned 21(Library used incorrectly)

How to solve it?

1 Answer 1

7

From the fine manual:

The flags parameter to sqlite3_open_v2() can take one of the following three values, [...]:

SQLITE_OPEN_READONLY
The database is opened in read-only mode. If the database does not already exist, an error is returned.

SQLITE_OPEN_READWRITE
The database is opened for reading and writing if possible, or reading only if the file is write protected by the operating system. In either case the database must already exist, otherwise an error is returned.

SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
The database is opened for reading and writing, and is created if it does not already exist. This is the behavior that is always used for sqlite3_open() and sqlite3_open16().

So you can't use just SQLITE_OPEN_CREATE, you need to include the SQLITE_OPEN_READWRITE bit if you want it to create the file:

retval = sqlite3_open_v2("v2.db", &ppdb,
                    SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, "unix-none");
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.