I am looking to perform some database operations programatically inside a Django application, namely, I want to:
Therefore, I have a number of possible options to try and utilise:
psycopg
package.with connection.cursor() as cursor
Assumptions:
What would be the some potential methods to achieve this? I need something like this but to talk between the two databases, source and target...
CREATE TABLE [Table to copy To]
AS [Table to copy From]
WITH NO DATA;
1) you can do it using 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) you can do it using 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) you can do it using 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'
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.