Problems with using FK, SQLITE3 and C

Asked

Viewed 55 times

0

I am having trouble recording records in my log table that has a client table FK. The error is in the insert_log function()

SQL to create tables

sql_create_client = "CREATE TABLE cliente (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, user_id TEXT NOT NULL, birthday TEXT NOT NULL, link TEXT NOT NULL, name TEXT NOT NULL, location TEXT NOT NULL, gender TEXT NOT NULL, email TEXT NOT NULL);";
sql_create_log = "CREATE TABLE log (id INTEGER NOT NULL PRIMARY KEY, created_at TEXT NOT NULL, fk_id INTEGER NOT NULL, FOREIGN KEY (fk_id) REFERENCES cliente(id));";

Inserting Log

int insert_log(char user_id[30]) { 
    int fk_id = user_exists(user_id);
    const char *created_at;
    sql_insert_log = "PRAGMA foreign_keys = 1; INSERT INTO log VALUES (?,?,?);";
    sql_query_log_datatime = "SELECT datetime('now', 'localtime');";

    if (connect_db() == 0) {

        sqlite3_prepare_v2(conn, sql_query_log_datatime, -1, &stmt, 0);

        if (sqlite3_step(stmt) == SQLITE_ROW) {
            created_at = sqlite3_column_text(stmt, 0);
            fprintf(stdout, "Result datetime: %s\n",created_at);


            sqlite3_prepare_v2(conn, sql_insert_log, -1, &stmt, NULL);

            sqlite3_bind_null(stmt,1);                  
            sqlite3_bind_text(stmt, 2, created_at, -1, SQLITE_STATIC);
            sqlite3_bind_int(stmt, 3, fk_id);

            sqlite3_step(stmt);
            sqlite3_finalize(stmt);

            close_db();
            return 0;
        } else return 1;

    } else {
        fprintf(stderr, "Cannot open database: %s\n", sqlite3_errmsg(conn));
        close_db();
        return 1;
    }       
}

Details: I am using Ubuntu and gcc. All client table querys work perfectly.

Part of the error was solved, it had a segmentation fault and I already took the part that caused:

Falha de segmentação (imagem do núcleo gravada)
O que causou:           sqlite3_reset(stmt);
  • 2

    What is the error? I noticed that you are running two queries in the same statement. Try to run the pragma at the moment you connect to the bank, since it needs to run only once per connection. Or try to run the pragma and the insert in different calls.

  • 2

    @Viníciusgobboa.deOliveira Your comment helped solve my problem. After following your advice, I managed to see another error where I didn’t correctly complete the statement and now everything is working.

  • cool! congratulations!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.