python - ON DUPLICATE KEY UPDATE 导致运行时错误

标签 python sqlite

我在两列之间有一个联合主键,我想第一次插入这些列,然后用旧值+新值更新它们,我使用 python 和 sqlite3 来执行此操作

这是我的代码:

db.execute(""" INSERT INTO transactions 
                          (user_id, name, symbol, shares, total)
                          VALUES 
                          (:user_id, :name, :symbol, :shares, :total ) 
                            ON DUPLICATE KEY UPDATE 
                            shares =shares+ :shares,
                            total = total + :total""",
                            user_id=session["user_id"],
                            name=q["name"],
                            symbol = q["symbol"],
                            shares=shares,
                            total=total
                          )

如果插入相同的符号和 user_id,我只想更新份额和总计,因为旧的份额值被添加到新的份额值,并且总计相同,这会给我带来接近 ON 的运行时错误,, ,任何帮助或提示表示赞赏

更新错误是:

RuntimeError: (sqlite3.OperationalError) near "ON": syntax error [SQL: " INSERT INTO transactions \n (user_id, name, symbol, shares, total)\n VALUES \n (16, 'Genpact Limited Common Stock', 'G', 5, 122.25 ) \n ON DUPLICATE KEY UPDATE \n shares = shares + VALUES(shares),\n total = total + VALUES(total)"]

最佳答案

INSERT statement没有 ON DUPLICATE 子句(在 SQLite 中)。

SQLite 是一个嵌入式数据库,没有客户端/服务器通信开销,因此没有必要尝试将多个内容压缩到单个 SQL 语句中。只需单独进行更新即可:

c = db.cursor()
c.execute("""UPDATE transactions
             SET shares = shares + :shares,
                 total = total + :total
             WHERE user_id = :user_id
               AND symbol = :symbol""",
          ...)
if c.rowcount == 0:
    c.execute("""INSERT INTO transactions ...""", ...)

关于python - ON DUPLICATE KEY UPDATE 导致运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42869675/

相关文章:

python - 使用列表寻找解决方案

python - openai.error.InvalidRequestError : Engine not found

python - 使用 python 创建用于发送 TCP 和 UDP 数据包的客户端和服务器程序

c# - System.Data.SQLite 参数未被替换

android - 为什么 Android Cursors 在第一行结果之前开始,在最后一行之后结束?

python - 如何配置 VS Code 以便能够进入调试 Python 脚本时加载的共享库 (.so)?

python - Pandas 系列和 Nan 值不匹配的值

java - SQL语法错误

java - 创建 SQLite 数据库时出错 : "android.database.sqlite.SQLiteException: near(9598)"?

sql - SQLite Delphi认为不正确的异常