[英]Python - UPDATE or INSERT to sqlite using dictionary
I am trying to UPDATE or INSERT if not exist rows into sqlite table.如果sqlite表中不存在行,我正在尝试更新或插入。 Can't manage to do this from python level using executemany无法使用executemany从 python 级别执行此操作
my input csv looks like this:我的输入 csv如下所示:
cfthostname,cftshortname,cftenv,cert_time
lx1234.pl.net,lx1234,tst,28/01/2021
plx169.net,plx169,tst,26/03/2021
sp2444445.net,sp2444445,prd,12/06/2021
my db model :我的数据库模型:
cfthostname,cftshortname,cftenv,cert_time
lx1234.pl.net,lx1234,tst,DD/MM/RRRR
plx169.net,plx169,tst,DD/MM/RRRR
sp2444445.net,sp2444445,prd,DD/MM/RRRR
what i need to do is:我需要做的是:
1. UPDATE cert_time column if cfthostname in input csv matches cfthostname in db如果在cfthostname输入CSV在分贝匹配cfthostname 1. UPDATE cert_time柱
2. INSERT all 4 columns if cfthostname does not exists in DB 2. 如果数据库中不存在cfthostname,则插入所有 4 列
db_update.py db_update.py
import sqlite3
import csv
conn = sqlite3.connect("C:\db.sqlite3")
cursor = conn.cursor()
[...]
######---Import to DB---######
cursor.execute("CREATE TABLE IF NOT EXISTS itpassed_host (cfthostname, cftshortname, cftenv, cert_time);")
with open('C:\csv\cfthosts.csv','rt') as fin:
dr = csv.DictReader(fin)
to_db = [(i['cfthostname'], i['cftshortname'], i['cftenv'], i['cert_time']) for i in dr]
cursor.executemany("INSERT INTO itpassed_host (cfthostname, cftshortname, cftenv, cert_time) VALUES (?, ?, ?, ?) ON CONFLICT (cfthostname) DO UPDATE SET cert_time=excluded.cert_time;", to_db)
conn.commit()
conn.close()
i get我明白了
sqlite3.OperationalError: near "ON": syntax error
i have sqlite 3.7.17我有 sqlite 3.7.17
Use "WHERE True" to avoid this conflict:使用“WHERE True”来避免这种冲突:
cursor.executemany("INSERT INTO itpassed_host (cfthostname, cftshortname, cftenv, cert_time) VALUES (?, ?, ?, ?) **WHERE True** ON CONFLICT (cfthostname) DO UPDATE SET cert_time=excluded.cert_time;", to_db)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.