我在两列之间有一个联合主键,我想第一次插入这些列,然后用旧值+新值更新它们,我使用 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/