【发布时间】:2012-09-16 05:17:48
【问题描述】:
我是个菜鸟,所以无法通过 psycopg2 插入 Postgresql。我有一个文件,其中包含以下行:
42::Dead Presidents (1995)::Action|Crime|Drama
43::Restoration::Drama
我正在尝试通过以下代码将这些行更改为插入语句:
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
【问题讨论】:
-
检查 Postgres 的日志。您看到的是最后一个错误,您需要第一个错误 - 导致整个事务失败的错误。
-
2012-09-15 22:48:42 CAT 声明:插入电影值 ('29', 'City of Lost Children, The (Cité des enfants perdus, La) (1995', '冒险|戏剧|奇幻|神秘|科幻','')
-
看不到该日志有任何问题,除了我的年份提取无法正常工作并且它可能在末尾需要一个分号。你认为是分号吗?
-
如果我只是用硬编码值调用它,即使我使用分号也会给出相同的错误
-
2012-09-16 07:48:10 CAT 错误:当前事务被中止,命令被忽略,直到事务块结束 2012-09-16 07:48:10 CAT 声明:插入电影值(1,'Dogma','Action',2010)2012-09-16 07:48:23 CAT ERROR:当前事务被中止,命令被忽略直到事务块结束 2012-09-16 07:48:23 CAT 声明: 插入电影值 (1, 'Dogma', 'Action', 2010); 2012-09-16 07:49:06 CAT 错误:当前事务被中止,命令被忽略,直到事务块结束
标签: python postgresql psycopg2