使用Python代码将记录从一个Oracle数据库复制到另一个数据库的过程可以通过以下步骤实现:
import cx_Oracle
import psycopg2
# Oracle数据库连接信息
oracle_host = "source_oracle_host"
oracle_port = "source_oracle_port"
oracle_service_name = "source_oracle_service_name"
oracle_username = "source_oracle_username"
oracle_password = "source_oracle_password"
# 建立Oracle数据库连接
oracle_conn = cx_Oracle.connect(oracle_username, oracle_password,
f"{oracle_host}:{oracle_port}/{oracle_service_name}")
oracle_cursor = oracle_conn.cursor()
# PostgreSQL数据库连接信息
postgres_host = "target_postgres_host"
postgres_port = "target_postgres_port"
postgres_database = "target_postgres_database"
postgres_username = "target_postgres_username"
postgres_password = "target_postgres_password"
# 建立PostgreSQL数据库连接
postgres_conn = psycopg2.connect(host=postgres_host, port=postgres_port,
dbname=postgres_database, user=postgres_username,
password=postgres_password)
postgres_cursor = postgres_conn.cursor()
# 执行查询语句
oracle_cursor.execute("SELECT * FROM source_table")
# 获取查询结果
records = oracle_cursor.fetchall()
# 插入数据到目标PostgreSQL数据库
for record in records:
postgres_cursor.execute("INSERT INTO target_table VALUES (%s, %s, %s)", record)
# 提交事务并关闭连接
postgres_conn.commit()
postgres_cursor.close()
postgres_conn.close()
完整代码示例:
import cx_Oracle
import psycopg2
# Oracle数据库连接信息
oracle_host = "source_oracle_host"
oracle_port = "source_oracle_port"
oracle_service_name = "source_oracle_service_name"
oracle_username = "source_oracle_username"
oracle_password = "source_oracle_password"
# PostgreSQL数据库连接信息
postgres_host = "target_postgres_host"
postgres_port = "target_postgres_port"
postgres_database = "target_postgres_database"
postgres_username = "target_postgres_username"
postgres_password = "target_postgres_password"
# 建立Oracle数据库连接
oracle_conn = cx_Oracle.connect(oracle_username, oracle_password,
f"{oracle_host}:{oracle_port}/{oracle_service_name}")
oracle_cursor = oracle_conn.cursor()
# 建立PostgreSQL数据库连接
postgres_conn = psycopg2.connect(host=postgres_host, port=postgres_port,
dbname=postgres_database, user=postgres_username,
password=postgres_password)
postgres_cursor = postgres_conn.cursor()
# 执行查询语句
oracle_cursor.execute("SELECT * FROM source_table")
# 获取查询结果
records = oracle_cursor.fetchall()
# 插入数据到目标PostgreSQL数据库
for record in records:
postgres_cursor.execute("INSERT INTO target_table VALUES (%s, %s, %s)", record)
# 提交事务并关闭连接
postgres_conn.commit()
postgres_cursor.close()
postgres_conn.close()
这个代码示例演示了如何使用Python将记录从一个Oracle数据库复制到另一个数据库。请根据实际情况修改连接信息、查询语句以及目标数据库的插入语句。
领取专属 10元无门槛券
手把手带您无忧上云