【问题标题】:How to copy a database table from one database to another如何将数据库表从一个数据库复制到另一个数据库
【发布时间】:2020-07-17 14:31:12
【问题描述】:

我希望在 Django 应用程序中以编程方式执行一些数据库操作,即,我想:

  • 将数据库 A 中的表 A 复制到数据库 B 中的表 A(保留表名),然后清理并删除表 A。

因此,我有许多可能的选择来尝试和使用:

  • 我可以尝试使用某种系统调用从应用程序中调用“pgdump”。
  • 我可能会使用psycopg 包。
  • 我更喜欢使用 Django 内置的with connection.cursor() as cursor

假设:

  • “表 A”存在于数据库 A 中,但“表 A”(架构和数据)在数据库 B 中不存在。
  • 数据库 A 和数据库 B 存在于不同的“主机”上

实现这一目标的一些潜在方法是什么?我需要这样的东西,但要在两个数据库之间进行对话,源和目标......

CREATE TABLE [Table to copy To]
AS [Table to copy From]
WITH NO DATA;

【问题讨论】:

  • 以下线程可能会对您有所帮助。 stackoverflow.com/questions/3195125/…
  • @prvreddy 不幸的是,您不能以编程方式执行此操作,密码需要用户输入。
  • @MichealJ.Roberts 是否需要复制表structurestructure and data
  • @DanilaGanchar 结构和数据

标签: python postgresql psycopg2 pg-dump django-3.0


【解决方案1】:

1)您可以使用dblink

# connect to pg
# psql -U user_here etc...
-- create a few db
create database first;
create database second;

-- connect to first db and create a table with a few records
\c first;

create table users
(
    id serial not null
        constraint users_pk
            primary key,
    name varchar(20) not null
);


INSERT INTO public.users (id, name) VALUES (1, 'first');
INSERT INTO public.users (id, name) VALUES (2, 'sec');
INSERT INTO public.users (id, name) VALUES (3, 'one_more');
INSERT INTO public.users (id, name) VALUES (4, 'etc');

-- connect to second db and copy table with data
\c second;
-- dblink -- executes a query in a remote database 
create extension dblink;

-- set your creds...
CREATE TABLE users AS SELECT * FROM dblink('dbname=first user=root password=root', 'select id, name from users') as tbl(id int, name varchar(20));

-- check data:
SELECT * FROM users;

2)您可以使用pg_dump

# generate dump with data of users table from first db
pg_dump -U root -d first --table=users --inserts > /tmp/users.dump
# run dump script on second db
psql -U root -d second < /tmp/users.dump;

3)您可以使用pandas

import pandas as pd
from sqlalchemy import create_engine


for df in pd.read_sql(
    'SELECT * FROM users',
    con=create_engine('postgres+psycopg2://root:root@localhost:5432/first', echo=True),
    chunksize=1000
):
    df.to_sql(
        con=create_engine('postgres+psycopg2://root:root@localhost:5432/second', echo=True),
        name='users',
        index=False,
        if_exists='append'
    )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-22
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多