如果使用执行人员存在数据,请更新行
我有以下SQL,旨在在数据库中创建新记录或更新现有记录。
sql = """INSERT INTO table (v1, v2, v3, v4, v5, v6)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(v5) DO UPDATE
SET v1 = ?, v3 = ?, v6 = ?
"""
self.curr.execute(sql,(
v1, v2, v3, v4, v5, v6,
# below are the values for eventual update
v1, v3, v6)
)
但是,这很棒,但是,我正在尝试使用executemany()
实现批处理创建,并且还将保留在冲突逻辑上。
我知道它看起来与此相似:
data = [
('Jane', date(2005, 2, 12)),
('Joe', date(2006, 5, 23)),
('John', date(2010, 10, 3)),
]
sql = """
INSERT INTO employees (first_name, hire_date)
VALUES (%s, %s)
ON CONFLICT(first_name) DO UPDATE
SET date = %S
"""
cursor.executemany(sql, data)
但是,如果使用first_name hire_date
) >
我已经存在数据阵列中的另外3个元组,并带有最终更新的值?
为了我的需要,我在网上找不到任何特定资源,因此将不胜感激。
I have the following SQL that aims to create a new record in the DB or update an existing one.
sql = """INSERT INTO table (v1, v2, v3, v4, v5, v6)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(v5) DO UPDATE
SET v1 = ?, v3 = ?, v6 = ?
"""
self.curr.execute(sql,(
v1, v2, v3, v4, v5, v6,
# below are the values for eventual update
v1, v3, v6)
)
This works great, however, I am trying to implement batch creation of rows with executemany()
, and also keep ON CONFLICT
logic.
I know that it would look something similar to this:
data = [
('Jane', date(2005, 2, 12)),
('Joe', date(2006, 5, 23)),
('John', date(2010, 10, 3)),
]
sql = """
INSERT INTO employees (first_name, hire_date)
VALUES (%s, %s)
ON CONFLICT(first_name) DO UPDATE
SET date = %S
"""
cursor.executemany(sql, data)
But I am not quite sure how to pass the columns value (hire_date
) that is used for the update if a row with first_name
already exists
Do I pass another 3 tuples in the data array with the values for an eventual update?
I couldn't find any specific resource on the web for my need, so any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将
排除
表限定符添加到列名:You can add the
EXCLUDED
table qualifier to the column name:由于您在SQL中有三个占位符,因此您需要绑定三个参数。因此,重复日期值。顺便说一句,
sqlite3
使用Qmark,?
,用于第一个示例中使用的占位符,并确保commit
。Because you have three placeholders in SQL you need to bind three parameters. Therefore, repeat the date value. By the way,
sqlite3
uses the qmark,?
, for placeholders as used in your first example and be sure tocommit
.