SQL Alchemy + Postgres + Python完整性错误

时间:2012-05-03 03:33:57

标签: python postgresql sqlalchemy

我有一个python应用程序,运行在2.7版本上,使用postgres 9.1和sqlalchemy 0.7我相信。

我有一个wx python gui,我可以从中添加和删除项目。代码工作正常,但现在我做了一些修改后收到了

$self.session.commit()
$  File "build\bdist.win32\egg\sqlalchemy\orm\session.py", line 645, in commit
$  File "build\bdist.win32\egg\sqlalchemy\orm\session.py", line 313, in commit
$  File "build\bdist.win32\egg\sqlalchemy\orm\session.py", line 297, in _prepare_impl
$  File "build\bdist.win32\egg\sqlalchemy\orm\session.py", line 1547, in flush
$  File "build\bdist.win32\egg\sqlalchemy\orm\session.py", line 1616, in _flush
$  File "build\bdist.win32\egg\sqlalchemy\orm\unitofwork.py", line 328, in execute
$  File "build\bdist.win32\egg\sqlalchemy\orm\unitofwork.py", line 472, in execute
$  File "build\bdist.win32\egg\sqlalchemy\orm\mapper.py", line 2291, in _save_obj
$  File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 1405, in execute
$ File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 1538, in           
$ _execute_clauseelement
$  File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 1646, in     
$_execute_context
$  File "build\bdist.win32\egg\sqlalchemy\engine\base.py", line 1639, in 
$_execute_context
$  File "build\bdist.win32\egg\sqlalchemy\engine\default.py", line 330, in do_execute
$sqlalchemy.exc.IntegrityError: (IntegrityError) duplicate key value violates
$ unique constraint "Equipment_pkey"
$DETAIL:  Key (id)=(4) already exists.
$ 'INSERT INTO "Equipment" (name, "numPorts") VALUES (%(name)s, %(numPorts)s)     
$RETURNING "HWCIs".id' {'numPorts': 0, 'name': u'jkhj'}

现在,当我重新启动应用程序时,密钥id增加了一个。我可以清楚地看到有些东西正在重置数据库的id序列。 anypne请帮助我如何解决这个问题,通过编写python代码或什么是解决这个问题的简单步骤。我尝试通过psql命令,但由于我缺乏知识,我没有成功。如果解决方案可以通过简单的步骤解释,这将是伟大的。

2 个答案:

答案 0 :(得分:1)

我找到了答案。我正在连接另一个数据库连接,导致数据库序列重置为1.因此,当应用程序启动时,它会寻找position 1。所以我只需要将sequence更改为last no。有效!

答案 1 :(得分:0)

日志中有所有内容:

您正在插入id = 4的行,但已存在具有此ID的行。

表中是否有id = 4的行?