1
我正在用Python編寫代碼,並使用psycopg2庫來處理我的PostgreSQL數據庫。Python/PostgreSQL - 如何使用psycopg2庫將表複製到另一個表?
我有表Orders
約30行。我想將整個表格複製到一個空白的表格中,名稱爲Orders2
。
我該怎麼做?
謝謝。
我正在用Python編寫代碼,並使用psycopg2庫來處理我的PostgreSQL數據庫。Python/PostgreSQL - 如何使用psycopg2庫將表複製到另一個表?
我有表Orders
約30行。我想將整個表格複製到一個空白的表格中,名稱爲Orders2
。
我該怎麼做?
謝謝。
雖然自己的答案是正確的,有不涉及傾銷到一個文件中,一般更靈活的是一個更好的辦法。
INSERT INTO orders2 SELECT * FROM orders
答案是:
import psycopg2
from psycopg2.extensions import ISOLATION_LEVEL_SERIALIZABLE
import sys
import cStringIO
con = psycopg2.connect(database="xxxx", user="xxxx", password="xxxx", host="localhost")
cur = con.cursor()
input = cStringIO.StringIO()
cur.copy_expert('COPY (select * from Orders) TO STDOUT', input)
input.seek(0)
cur.copy_expert('COPY Orders2 FROM STDOUT', input)
con.commit()