简体   繁体   中英

Cursor.execute with

So I'm trying to run a sql command using cursor.execute where

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))

Tried

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)

I'm getting this error now

   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 ...

How do I do both an insert with a where clause?

You have an extra close-bracket after the placeholders and your subquery needs some touching up. Try instead:

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))

Hrm, maybe that syntax is illegal. Try this instead:

curs.execute("""INSERT INTO customers (c,n,b,f) 
                VALUES (%s,%s,%s,%s) 
                ON CONFLICT (customerid) DO NOTHING);""",(cid,name,bdate,ffon,cid))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM