有一个写数据到表的大脚本,需要从数据库中导出过时的数据进行存储
def export_data(cursor, name, connection):
try:
print(f''' COPY '{name}' TO '/tmp/databases/{name}/{name}_{datetime.now().strftime("%d_%m_%y")}.csv' WITH (FORMAT CSV, HEADER) ''')
insert_table_query = f''' COPY '{name}' TO '/tmp/databases/{name}/{name}_{datetime.now().strftime("%d_%m_%y")}.csv' WITH (FORMAT CSV, HEADER) '''
cursor.execute(insert_table_query)
connection.commit()
except Exception and errors as e:
print(e)
错误
Connection to PostgreSQL DB successful
COPY 'sprint' TO '/tmp/databases/sprint/sprint_30_08_22.csv' WITH (FORMAT CSV, HEADER)
catching classes that do not inherit from BaseException is not allowed
不完全清楚如何实现表暴露
pcycopg2 库有一个原生的.copy_to()方法
我的决定
cursor.copy_to(f'/tmp/databases/{name}/{name}_{datetime.now().strftime("%d_%m_%y")}.csv')