【问题标题】:Insert Data with Foreign Key Constraint Not Working? [SQLite with C++]插入带有外键约束的数据不起作用? [使用 C++ 的 SQLite]
【发布时间】:2020-06-19 07:54:22
【问题描述】:

我正在尝试通过在引用原始表的临时表中创建外键来通过 sqlite 检查用户想要删除的记录是否存在,遗憾的是这不起作用,我是否遗漏了一些明显的东西?

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;
        }
    }

我必须添加更多的文字才能发布,如果这是人为错误而不是更复杂的事情,对不起!

【问题讨论】:

    标签: c++ sqlite c++11


    【解决方案1】:

    您不能拥有引用另一个附加数据库中的表的外键。因此,用于临时表的 temp 数据库架构中的表不能使用 main 数据库架构中的表作为外键的父表。

    如果你尝试这样做:

    sqlite> pragma foreign_keys=on;
    sqlite> create table foo(id integer primary key, x);
    sqlite> create temp table bar(id integer primary key, foo_id integer references foo(id));
    sqlite> insert into foo values (1, 'dog');
    sqlite> insert into bar values (1, 1);
    Error: no such table: temp.foo
    

    如您所见,它在 temp 架构中查找父表,但没有找到它。尝试限定表格不起作用:

    sqlite> create temp table bar(id integer primary key, foo_id integer references main.foo(id));
    Error: near ".": syntax error
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多