Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python psycopg2 not inserting into postgresql table

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" 
like image 636
Superdooperhero Avatar asked Aug 05 '13 22:08

Superdooperhero


1 Answers

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" 
like image 139
aright Avatar answered Sep 23 '22 12:09

aright