错误:尝试将主键重新定义为非主键

2024-06-28 19:02:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用dataset库尝试将postgres数据库备份到sqlite文件中。我运行的代码如下:

local_db = "sqlite:///backup_file.db"

with dataset.connect(local_db) as save_to:
    with dataset.connect(postgres_db) as download_from:

        for row in download_from['outlook']:
            save_to['outlook'].insert(row)

如果打印表中的一行,则如下所示:

^{pr2}$

但是,当我到达save_to['outlook'].insert(row)行时,我得到一个错误,其中包含以下堆栈跟踪:

Traceback (most recent call last):
  File "/home/anton/Development/Python/TTC/backup_db.py", line 25, in <module>
    save_to['outlook'].insert(dict(row))
  File "/home/anton/.virtualenvs/flexity/lib/python3.6/site-packages/dataset/table.py", line 79, in insert
    row = self._sync_columns(row, ensure, types=types)
  File "/home/anton/.virtualenvs/flexity/lib/python3.6/site-packages/dataset/table.py", line 278, in _sync_columns
    self._sync_table(sync_columns)
  File "/home/anton/.virtualenvs/flexity/lib/python3.6/site-packages/dataset/table.py", line 245, in _sync_table
    self._table.append_column(column)
  File "/home/anton/.virtualenvs/flexity/lib/python3.6/site-packages/sqlalchemy/sql/schema.py", line 681, in append_column
    column._set_parent_with_dispatch(self)
  File "/home/anton/.virtualenvs/flexity/lib/python3.6/site-packages/sqlalchemy/sql/base.py", line 431, in _set_parent_with_dispatch
    self._set_parent(parent)
  File "/home/anton/.virtualenvs/flexity/lib/python3.6/site-packages/sqlalchemy/sql/schema.py", line 1344, in _set_parent
    self.key, table.fullname))
sqlalchemy.exc.ArgumentError: Trying to redefine primary-key column 'id' as a non-primary-key column on table 'outlook'

你知道我做错了什么吗?我已经在python2.7.14和3.6.3中尝试过这种方法


Tags: inpyselfhomelibpackageslinetable
2条回答

假设您有一个为“outlook”创建的架构和表,那么您是否创建了PK字段?你让sqlite决定哪个字段组成PK字段了吗?在

你试图插入id两次是非常重要的。一旦sqlite插入了自己,其他的则来自其他表记录。在

我想出来了!所以,诀窍在于,默认情况下,database库生成具有自动递增整数主键的表。但是,我的数据已经有一个'id'列。为了避免这个问题,我应该在尝试向表中添加行之前定义表,并且定义它时不使用主键,如下所示:

with dataset.connect(local_db) as save_to:
    with dataset.connect(postgres_db) as download_from:

        table_to_save_to = save_to.create_table('outlook', primary_id=False)

        for row in download_from['outlook']:
            table_to_save_to.insert(row)

通过执行.create_table(table_name, primary_key=False)操作,我可以确保可以在表中插入我自己的id值。在

我通过reading the docs找到了这个解决方案。在

相关问题 更多 >