Superdooperhero
Superdooperhero

Reputation: 8096

Python insert via psycopg2 into postgresql failing

I'm a noob so having trouble with inserting into Postgresql via psycopg2. I have a file with lines such as:

42::Dead Presidents (1995)::Action|Crime|Drama
43::Restoration::Drama

I'm trying to change those lines into insert statements via the following code:

import psycopg2

try:
   db = psycopg2.connect("dbname='db' user='postgres' host='localhost' password='password'")
   cur = db.cursor()
except:
   print("Unable to connect to the database.")

for line in open('./movies.dat'):
   (movie_id, movie_name, tags) = line.split('::')[0:3]
   ypos = movie_name.rfind('(')
   ypos2 = movie_name.rfind(')')
   if ypos < 0:
      cur.execute("insert into movies values (%s, %s, %s, null)", (movie_id, movie_name, tags))
   else:
      cur.execute("insert into movies values (%s, %s, %s, %s)", (movie_id, movie_name[0:ypos].strip(), tags, movie_name[ypos+1:ypos2].strip()))

Unfortunately I get the error:

Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block

I have no idea why, or how to go about debugging the general error of psycopg2. Anybody have any helpful ideas?

This is python 3.2.3 and postgresql 9.2

Upvotes: 0

Views: 1094

Answers (1)

Brendan Long
Brendan Long

Reputation: 54312

except:
    print("Unable to connect to the database.")

You're ignoring a fatal error. You should:

  1. Print a more useful error message (containing the actual error)
  2. Stop execution (either remove this catch statement and let the exception propagate up, or return an error code).

Upvotes: 1

Related Questions