使用psycopg2 copy_from和copy_expert复制表?

Bri*_*n B 4 python postgresql psycopg2

我想使用psycopg2中提供的复制命令将旧数据库中的表行复制到新数据库中.我想我可以通过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()
Run Code Online (Sandbox Code Playgroud)

记录显示我应该获得30,000行.但是,尽管缺少错误消息,但我没有获得新行.为了它的价值,检查io.read()节目的长度为零.

我怎样才能做到这一点?

Bri*_*n B 6

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

io.seek(0)
Run Code Online (Sandbox Code Playgroud)