'Python SQL Insert script
I'm creating a Python script to insert some records in a table, but have the following problem:
INSERT INTO orders VALUES (7656940929251, "ADIDAS | KID'S STAN SMITH")
,(242345235233, 'ADIDAS | CLASSIC BACKPACK')
I get the error: "Invalid column name 'ADIDAS | KID'S STAN SMITH'
How can I fix this with Python?
Solution 1:[1]
Let's say this is your tuple:
tuples_v3s = ((7656941224163, 'ADIDAS | CLASSIC BACKPACK'),
(7656941256931, 'ADIDAS | CLASSIC BACKPACK | LEGEND INK MULTICOLOUR'),
(7656940929251, "ADIDAS | KID'S STAN SMITH"))
for tuples_v3 in tuples_v3s:
print(f"""INSERT INTO orders VALUES ({tuples_v3[0]},'{tuples_v3[1].replace("'","''")}' ) """)
#INSERT INTO orders VALUES (7656941224163,'ADIDAS | CLASSIC BACKPACK' )
#INSERT INTO orders VALUES (7656941256931,'ADIDAS | CLASSIC BACKPACK | LEGEND INK MULTICOLOUR' )
#INSERT INTO orders VALUES (7656940929251,'ADIDAS | KID''S STAN SMITH' )
Solution 2:[2]
If you are using psycopg2, Please update your query as below
insert_query = "INSERT INTO products VALUES (7656941224163, %s),
(7656941256931, %s),
(7656940929251, %s)"
cur.execute(insert_query, ("ADIDAS | CLASSIC BACKPACK", "ADIDAS | CLASSIC BACKPACK | LEGEND INK MULTICOLOUR", "ADIDAS | KID'S STAN SMITH"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Sreejith V |
