c++ - 更新返回 0 即使表中没有此 id

标签 c++ sql sqlite

我在 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/

相关文章:

ruby-on-rails - sqlite3在 rails 上:create_table使用collat​​e nocase

排序函数中的 C++ 错误

c++ - 不能覆盖派生类中的静态初始化

c++ - 递归显式模板实例化是否可能?

sql - 3NF 数据库规范化

mysql - 如何根据最小日期行中的条件返回最大日期结果?

sql - mysql:平均一行中的多列,忽略空值

c++ - SQLite 无法在 Win98 中打开数据库

c# - SQLite.net 表查询抛出 NullReferenceException

sqlite - 两列使用 SqlAlchemy 加入同一个表