Python psycopg2 not inserting into postgresql table

PythonPostgresqlInsertPsycopg2

Python Problem Overview


I'm using the following to try and insert a record into a postgresql database table, but it's not working. I don't get any errors, but there are no records in the table. Do I need a commit or something? I'm using the postgresql database that was installed with the Bitnami djangostack install.

import psycopg2

try:
    conn = psycopg2.connect("dbname='djangostack' user='bitnami' host='localhost' password='password'")
except:
    print "Cannot connect to db"

cur = conn.cursor()

try:
    cur.execute("""insert into cnet values ('r', 's', 'e', 'c', 'w', 's', 'i', 'd', 't')""")
except:
    print "Cannot insert"

Python Solutions


Solution 1 - Python

If don't want to have to commit each entry to the database, you can add the following line:

conn.autocommit = True

So your resulting code would be:

import psycopg2

try:
    conn = psycopg2.connect("dbname='djangostack' user='bitnami' host='localhost' password='password'")
    conn.autocommit = True
except:
    print "Cannot connect to db"

cur = conn.cursor()

try:
    cur.execute("""insert into cnet values ('r', 's', 'e', 'c', 'w', 's', 'i', 'd', 't')""")
except:
    print "Cannot insert"

Solution 2 - Python

Turns out I needed conn.commit() at the end

Solution 3 - Python

psycopg2 is Python DB API-compliant, so the auto-commit feature is off by default. You need to call conn.commit to commit any pending transaction to the database. As connections (and cursors) are context managers, you can simply use the with statement to automatically commit/rollback a transaction on leaving the context:

with conn, conn.cursor() as cur:  # start a transaction and create a cursor
    cur.execute(sql)

From the docs:

> When a connection exits the with block, if no exception has been > raised by the block, the transaction is committed. In case of > exception the transaction is rolled back. > > When a cursor exits the with block it is closed, releasing any > resource eventually associated with it. The state of the transaction > is not affected.

Solution 4 - Python

import psycopg2
conn = psycopg2.connect("dbname='djangostack' user='bitnami' 
host='localhost' password='password'")
con.set_session(autocommit=True)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSuperdooperheroView Question on Stackoverflow
Solution 1 - PythonarightView Answer on Stackoverflow
Solution 2 - PythonSuperdooperheroView Answer on Stackoverflow
Solution 3 - PythonEugene YarmashView Answer on Stackoverflow
Solution 4 - Pythonheaven2saiView Answer on Stackoverflow