post.cres中的cursor.copy_from失败

时间:2012-12-21 15:18:03

标签: python postgresql cursor psycopg2 sqlbulkcopy

我在将数据从一个数据库复制到另一个数据库时遇到问题这里是python代码。

import psycopg2

db = psycopg2.connect("dbname='db' user='xx' password='xx' host='127.0.0.2'")
st = db.cursor();

db_l = psycopg2.connect("dbname='xx' user='xx' password='xx' host='127.0.0.1'")
st_l = db_l.cursor();


q = "create table tarf as select i_rate, i_tariff As id, prefix, price_1, price_n, interval_1, interval_n, '00:00' AS start_time, '23:59:59' AS end_time, activation_dat
e, '3049-1-1 00:00' as exp  from rates JOIN tariffs USING (i_tariff) JOIN billing_plans USING(i_tariff) JOIN accounts using (i_billing_plan)"

st_l.execute(q)

f = open('tariff.sql','w')
st_l.copy_to(f,'tarf',sep=',')

st.copy_from(f,'tariff',sep=',')

这是一个面临的错误:

Traceback (most recent call last):
  File "sync_tariff.py", line 23, in <module>
    st.copy_from(f,'tariff',sep=',')
psycopg2.extensions.QueryCanceledError: COPY from stdin failed: error in .read() call
CONTEXT:  COPY tariff, line 1

1 个答案:

答案 0 :(得分:1)

关闭文件,然后将其打开以进行阅读

f = open('tariff.sql', 'w')
st_l.copy_to(f, 'tarf', sep=',')

f.close()

f = open('tariff.sql', 'r')
st.copy_from(f, 'tariff', sep=',')