簡體   English   中英

Python通過psycopg2插入到PostgreSQL失敗

[英]Python insert via psycopg2 into postgresql failing

我是菜鳥,因此無法通過psycopg2插入Postgresql。 我有一個帶有以下行的文件:

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

我正在嘗試通過以下代碼將這些行更改為insert語句:

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()))

不幸的是我得到了錯誤:

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

我不知道為什么,或如何調試psycopg2的一般錯誤。 有人有什么有用的想法嗎?

這是python 3.2.3和PostgreSQL 9.2

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

您忽略了一個致命錯誤。 你應該:

  1. 打印更有用的錯誤消息(包含實際錯誤)
  2. 停止執行(刪除此catch語句並讓異常傳播,或返回錯誤代碼)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM