4

I'm writing the code in Python and am using the psycopg2 library to deal with my PostgreSQL database.

I have the table Orders with about 30 rows. I want to copy this entire table to an empty one with the same structure called Orders2.

How can I do this?

Thank you.

2 Answers 2

8

The answer is:

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()
Sign up to request clarification or add additional context in comments.

1 Comment

This is great for copying table to a different DB, just have two connections.
3

While your own answer is correct, there is a better way that does not involve dumping to a file and is generally more flexible.

INSERT INTO orders2 SELECT * FROM orders

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.