【问题标题】:Copying a table using psycopg2 copy_from and copy_expert?使用 psycopg2 copy_from 和 copy_expert 复制表?
【发布时间】:2012-12-19 18:37:15
【问题描述】:

我想使用 psycopg2 中的copy 命令将旧数据库中的表行复制到新数据库中。我以为我可以通过StringIO 重定向,如下所示

io = StringIO.StringIO('')
whereClause = " SELECT %s FROM %s WHERE home_city='%s' "%(
                 ','.join(columns), tablename, city,
                     )
old_db_cursor.execute(whereClause)
rows = old_db_cursor.fetchall()
logger.info('Should get %d rows',len([r for r in rows]))
sql = 'COPY (%s) to STDOUT'%(whereClause,)
old_db_cursor.copy_expert( sql, io,  )
new_db_cursor.copy_from( io, tablename, columns=columns)
new_db_connection.commit()

日志显示我应该得到 30,000 行。但是尽管没有错误消息,但我没有得到新的行。对于它的价值,检查io.read() 的长度显示它为零。

我怎样才能做到这一点?

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

    回答我自己的问题,有必要倒回StringIO对象,使用

    io.seek(0)
    

    【讨论】:

    • 我花了一个多小时试图弄清楚为什么copy_from 不能让它成为这样。他们确实需要在文档中发出警告才能做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2020-07-01
    • 2012-04-21
    • 2022-01-08
    相关资源
    最近更新 更多