vendredi 6 mars 2020

Insert Data with Foreign Key Constraint Not Working? [SQLite with C++]

I'm trying to check the record the user wants to delete exists via sqlite by creating a foreign key in a temporary table referencing the original table, sadly this is not functioning, am I missing something obvious?

void enableForeignKeys()
    {
        const char* sql = "PRAGMA foreign_keys = ON;";

        int writeToDB = sqlite3_exec(db, sql, callback, 0, &errorMessage);

        if (writeToDB != SQLITE_OK) {
            cerr << "SQL error: %s" << &errorMessage << endl;
            sqlite3_free(errorMessage);
        }
        else {
            sql = "PRAGMA foreign_keys;";
            sqlite3_exec(db, sql, callback, 0, &errorMessage);
            return;
        }
    };

bool verifyEntryChoice(string referenceTable, string referencePrimaryKeyColumn, string chosenID)
    {
        sqlite3_open(filePath, &db);
        enableForeignKeys();

        string createTableQuery = "CREATE TEMP TABLE temp("
            "tempID INT UNIQUE NOT NULL,"
            "FOREIGN KEY(tempID) REFERENCES Customer(CustomerID));";

        const char* createTableSQL = &createTableQuery[0];
        cout << createTableSQL << endl;

        int writeToDB = sqlite3_exec(db, createTableSQL, callback, 0, &errorMessage);

        if (writeToDB != SQLITE_OK) {
            cerr << "Error" << endl;
            return false;
        }
        else cout << "Table created" << endl;

        string insertQuery = "INSERT INTO temp(tempID)"
            " VALUES(1);";

        const char* insertSQL = &insertQuery[0];
        cout << insertSQL << endl;

        writeToDB = sqlite3_exec(db, insertSQL, callback, 0, &errorMessage);

        if (writeToDB != SQLITE_OK) {
            cerr << "Wrong ID!" << endl;
            return false;
        }
        else {
            cout << "ID verified" << endl;
            return true;
        }
    }

I have to add more words for this to be posted apparently, sorry if it's human error and not something more complex!

Aucun commentaire:

Enregistrer un commentaire