fbpx

Copy Table From one PostgreSQL RDS to Another using Python Boto3

To copy a table from one PostgreSQL RDS instance to another using Python and boto3, you will need to:

  1. Install the Python library psycopg2, which is a PostgreSQL adapter for Python. You can do this by running pip install psycopg2 in your terminal.

  2. Import the necessary modules:​

				
					import boto3
import psycopg2

				
			
  1. Connect to both the source and target RDS instances using the psycopg2 library. You will need to specify the host, port, database name, username, and password for each RDS instance.

  2. Once you have established connections to both RDS instances, you can use the psycopg2 library to create a cursor object for each connection. A cursor allows you to execute PostgreSQL commands and retrieve data.

  3. Use the cursor to execute a SELECT statement on the source table. This will retrieve all of the rows from the table.

  4. Iterate over the rows returned by the SELECT statement, and use the cursor for the target RDS instance to execute an INSERT statement for each row. This will copy the data from the source table to the target table.

Here is some sample code that demonstrates how to do this:

				
					# Connect to the source RDS instance
conn1 = psycopg2.connect(host="source-rds-instance.abc123.us-east-1.rds.amazonaws.com", port=5432, database="mydatabase", user="myuser", password="mypassword")
cur1 = conn1.cursor()

# Connect to the target RDS instance
conn2 = psycopg2.connect(host="target-rds-instance.abc123.us-east-1.rds.amazonaws.com", port=5432, database="mydatabase", user="myuser", password="mypassword")
cur2 = conn2.cursor()

# Select all rows from the source table
cur1.execute("SELECT * FROM mytable")

# Iterate over the rows and insert them into the target table
for row in cur1:
    cur2.execute("INSERT INTO mytable VALUES (%s, %s, %s)", row)

# Commit the changes to the target RDS instance
conn2.commit()

# Close the cursors and connections
cur1.close()
conn1.close()
cur2.close()
conn2.close()

				
			

I hope this helps! Let me know if you have any questions.

Share:

Facebook
Twitter
Pinterest
LinkedIn

Social Media

Most Popular

Get The Latest Updates

Subscribe To Our Weekly Newsletter

No spam, notifications only about new products, updates.

Categories