简体   繁体   English

使用pg_dump创建Python PostgreSQL表

[英]Python PostgreSQL table creation using pg_dump

I'm trying to replicate the table structure of an existing PostgreSQL database. 我正在尝试复制现有PostgreSQL数据库的表结构。 I have 2 databases currently, A and B. I used the "pg_dump -s" command and generated the sql query to create the tables of A. In my python script, I have the following code to create the same structure in database B: 我目前有2个数据库,A和B。我使用“ pg_dump -s”命令并生成了sql查询来创建A的表。在我的python脚本中,我有以下代码在数据库B中创建相同的结构:

con2 = psycopg2.connect(database="Archives", user="postgres", password="root", host="127.0.0.1", port="5432")

dbexe = """
--
-- PostgreSQL database dump
--

-- Dumped from database version 9.6.0
-- Dumped by pg_dump version 9.6.0

SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;

--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner: 
--

CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;


--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: 
--
several thousand more lines ...."""

cur2 = con2.cursor()
cur2.execute(dbexe)
print("done")

The code seems to run fine but when I check database BI don't see any tables. 该代码似乎运行良好,但是当我检查数据库BI时看不到任何表。 Any suggestions as to why this may be happening? 关于为什么会发生这种情况的任何建议?

You must commit the transaction at the end because by default any data manipulation is rolled back and lost. 您必须在最后commit事务,因为默认情况下,任何数据操作都会回滚并丢失。

cur.commit()

Alternatively, you can set autocommit to True at the beginning to commit each new data automatically to the db. 或者,您可以在开始时将autocommit设置为True ,以将每个新数据自动提交给数据库。

conn.autocommit = True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM