簡體   English   中英

使用pg_dump創建Python PostgreSQL表

[英]Python PostgreSQL table creation using pg_dump

我正在嘗試復制現有PostgreSQL數據庫的表結構。 我目前有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")

該代碼似乎運行良好,但是當我檢查數據庫BI時看不到任何表。 關於為什么會發生這種情況的任何建議?

您必須在最后commit事務,因為默認情況下,任何數據操作都會回滾並丟失。

cur.commit()

或者,您可以在開始時將autocommit設置為True ,以將每個新數據自動提交給數據庫。

conn.autocommit = True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM