0

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

4

1 回答 1

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

您忽略了一个致命错误。你应该:

  1. 打印更有用的错误消息(包含实际错误)
  2. 停止执行(要么删除此 catch 语句并让异常向上传播,要么返回错误代码)。
于 2012-09-15T21:17:48.250 回答