0

How can one dump a PostgreSQL database programmatically, inside Python (or another language, if possible) without executing shell scripts.

Is this possible with psychopg2 or SQLAlchemy or some other library?

I want to dump all contents of the database, not just the schema. I do not want to dump the contents of just a query.

Currently I am using pg_dump -h localhost -U user -d db > db_dump.sql, however I would like to make use of a library to do this with python code.

The solutions I have already found typically resort to something along the lines of:

os.system(" pg_dump -h localhost -U user -d db > db_dump.sql ")

however this just asks the host machine to run the C implementation of pg_dump.

Similarly, I notice one can dump the contents of a query using something like:

cursor.execute(SELECT x FROM t)

f = open(db_dump.sql)

for row in cursor:

f.write("insert into t values (" + str(row) + ");")

However I want to save the contents of the entire database, not just a single query.

Can it be done with python directly?

2
  • You can't, you will need to use the pg_dump command. Commented Feb 8, 2023 at 1:10
  • You would have to interface Python to the underlying libraries, and possibly write your own implementation of pg_dump in Python, see thread (note the mention of libpq). Another related thread. Commented Feb 8, 2023 at 1:12

0

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.