所以我正在尝试使用cursor.execute运行一个sql命令
cid = data[key]['customerid']
name = data[key]['name']
bdate = data[key]['birthdate']
ffon = data[key]['frequentflieron']
curs.execute("INSERT INTO customers (c,n,b,f) VALUES (%s,%s,%s,%s)) WHERE NOT EXISTS (Select 1 FROM customers WHERE customerid = (c) VALUES (%s));",(cid,name,bdate,ffon,cid))
尝试
curs.execute("""INSERT INTO customers (c,n,b,f)
VALUES (%s,%s,%s,%s) WHERE NOT EXISTS (
Select 1
FROM customers
where customerid = %s);""",(cid,name,bdate,ffon,cid)
我现在收到此错误
Traceback (most recent call last):
File "psy.py", line 44, in <module>
custinfo(data,key)
File "psy.py", line 28, in custinfo
where customerid = %s);""",(cid,name,bdate,ffon,cid))
psycopg2.ProgrammingError: syntax error at or near "WHERE"
LINE 2: ...ust1000','XYZ','1991-12-06','Southwest Airlines') WHERE NOT ...
如何使用where子句进行插入?
答案 0 :(得分:1)
在占位符和子查询需要一些修饰之后,你有一个额外的近似括号。请尝试改为:
curs.execute("""INSERT INTO customers (c,n,b,f)
VALUES (%s,%s,%s,%s) WHERE NOT EXISTS (
Select 1
FROM customers
where customerid = %s);""",(cid,name,bdate,ffon,cid))
嗯,也许这种语法是非法的。试试这个:
curs.execute("""INSERT INTO customers (c,n,b,f)
VALUES (%s,%s,%s,%s)
ON CONFLICT (customerid) DO NOTHING);""",(cid,name,bdate,ffon,cid))