我在 visual studio 中使用 sqlite。
我正在尝试更新我的表中不存在的记录。
代码如下:
const char* sqlUpdateTable = "UPDATE MyTable SET name = '25th' WHERE id = 25;";
rc = sqlite3_exec(db, sqlUpdateTable, NULL, NULL, &error);
if (rc)
{
cerr << "Error executing SQLite3 statement: " << sqlite3_errmsg(db) << endl << endl;
sqlite3_free(error);
}
else
{
cout << "Updated MyTable." << endl << endl;
}
我将始终看到“更新的 MyTable”。然而,它没有。
最佳答案
您的实际问题:
I need to update a specific record, ex: PRIMARY KEY id = 10, if this record doesn't exist, I need to insert it.
现代版本的 Sqlite 支持 Postgres 风格 UPSERT符号:
INSERT INTO myTable(id, name) VALUES (25, '25th') ON CONFLICT (id) DO UPDATE SET name = '25th';
假设 id
是主键或唯一列,这将插入一个新行或使用该 id
更新现有行的名称列。
旧版本可以使用INSERT OR REPLACE得到类似的东西:
INSERT INTO myTable(id, name) VALUES (25, 'Original Name');
-- At some later point...
INSERT OR REPLACE INTO myTable(id, name) VALUES (25, '25th');
来自REPLACE conflict resolution文档:
When a UNIQUE or PRIMARY KEY constraint violation occurs, the REPLACE algorithm deletes pre-existing rows that are causing the constraint violation prior to inserting or updating the current row and the command continues executing normally.
关于c++ - 更新返回 0 即使表中没有此 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56469927/