user2628641
user2628641

Reputation: 2154

Python Postgres how to insert

try:
    conn = psycopg2.connect("dbname='test1' user='postgres' host='localhost' password='123'")
    cur = conn.cursor()
    cur.execute("""INSERT INTO product_info (product_name) VALUES (%s)""", 'xxx')
except:
    print "error happens"

The above is my code snippet, I have no trouble connecting to the database, but I have some problem inserting the value into it.

I execute the same query in postgres and it works, so i think it's a syntax problem.

Can someone show me what is the right way to do insertion?

Upvotes: 0

Views: 199

Answers (1)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125204

cur.execute("""
    insert into product_info (product_name) VALUES (%s)
""", ('xxx',))
conn.commit()

Notice that the value is passed to the method wrapped in an iterable.

Upvotes: 1

Related Questions