简体   繁体   中英

Creating an sqlite3 table in c++

I'm experimenting with C++, having recently moved across from python; currently writing a function that builds a table in an sqlite3 database.

I seem to be hitting some newbie errors:

int db_build()
{
   sqlite3 *db;
   int rc; // This line
   int sql; // This line
   rc = sqlite3_open("test.db", &db);

   /* Create SQL statement */
   sql = "CREATE TABLE WORDS("  \
         "ID INT PRIMARY        KEY      NOT NULL," \
         "CURRENT_WORD          TEXT     NOT NULL," \
         "BEFORE_WORD           TEXT     NOT NULL," \
         "AFTER_WORD            TEXT     NOT NULL," \
         "OCCURANCES            INT      NOT NULL);";

   /* Execute SQL statement */
   rc = sqlite3_exec(db, sql);
   sqlite3_close(db);
   return 0;
}

My terminal returns the following:

akf@akf-v5 ~/c/HelloWorld $ g++ main.cpp -l sqlite3
main.cpp: In function ‘int db_build()’:
main.cpp:30:8: error: invalid conversion from ‘const char*’ to ‘int’ [-fpermissive]
    sql = "CREATE TABLE WORDS("  \
        ^
main.cpp:38:29: error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]
    rc = sqlite3_exec(db, sql);
                             ^
main.cpp:38:29: error: too few arguments to function ‘int sqlite3_exec(sqlite3*, const char*, int (*)(void*, int, char**, char**), void*, char**)’
In file included from main.cpp:4:0:
/usr/include/sqlite3.h:379:16: note: declared here
 SQLITE_API int sqlite3_exec(
                ^

If I change 'int sql' to 'char sql' I hit even more errors. Any idea how to get this thing going?

You have one syntax error. Get rid of the trailing \\

/* Create SQL statement */
sql = "CREATE TABLE WORDS("  
      "ID INT PRIMARY        KEY      NOT NULL," 
      "CURRENT_WORD          TEXT     NOT NULL," 
      "BEFORE_WORD           TEXT     NOT NULL," 
      "AFTER_WORD            TEXT     NOT NULL," 
      "OCCURANCES            INT      NOT NULL);";

And one python-y error. Change int sql; to:

const char sql[];

The type const char sql[] is appropriate for constant string literals.

Edit:

For completeness, Hot Licks also hints that your call to sqlite3_exec must be:

rc = sqlite3_exec(db, sql, NULL, NULL, NULL);

If you're going to code in C++ you'd better very quickly learn what a pointer is, and what a "C string" is.

sqlite3_exec expects a C string as the second argument, which is a sequence of 8-bit char values terminated with a byte of zeros. It is passed via a pointer-to-char -- char * .

So your declaration needs to be char * sql; .

Also, if you look at the documentation you will see that sqlite3_exec has several more parameters -- they cannot be omitted (though they can be passed as NULL ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM