1. Install psycopg2,cx_oracle using pip.
  2. Second, Establish a PostgreSQL & Oracle database connection in Python.
  3. Next, Define the Select & Insert query
  4. Execute the INSERT query using cursor. …
  5. After the successful execution of the query, commit your changes to the database

Here is the sample code where I can trying to get all table row counts from Postgres Database to Oracle Database and inserting into table

# October 2022 Sandeep Reddy Narani
# I will get PostgreSQL Database tables row count and insert into oracle database table.
import psycopg2;
import cx_Oracle;
import config;
pgsql = "select table_schema as pg_table_schema, table_name as pg_table_name, count_rows_of_table(table_schema, table_name) as pg_rows from information_schema.tables where  table_schema not in ('pg_catalog', 'information_schema') and table_type = 'BASE TABLE' order by 1 asc, 3 desc;"
oraconn = cx_Oracle.connect('system/"pswd"@scan-hostname/service or sid name')
ora_inst_stmt9 = 'INSERT INTO  SCOTT.PG_TBROWCONT(PG_TABLE_SCHEMA,PG_TABLE_NAME,PG_ROWS) VALUES (:1 ,:2,:3)'
#oraconn = cx_Oracle.connect( config.username, config.password, config.dsn, encoding=config.encoding)
pgconn = psycopg2.connect(
   database="dbadeeds", user='scott', password='iV#', host='hostname', port= '5432'
)
#Creating a cursor object using the cursor() method
pgcurr1 = pgconn.cursor();
orcurr1 = oraconn.cursor();
orcurr1.execute('TRUNCATE TABLE SCOTT.PG_TBROWCONT')
#orcurr1.autocommit = True
#Executing an PG function using the execute() method
pgcurr1.execute(pgsql)
orarecs=[]
orarecsbatch=[]
recctr = 0
batchctr = 0
while True:
    all_trigs = pgcurr1.fetchmany(size=250)
    #print(all_trigs)
    if not all_trigs:
        break
    for trig in all_trigs:
        orarecs.append(trig[0])
        orarecs.append(trig[1])
        orarecs.append(trig[2])
        orarecsbatch.append(orarecs)
        #print(orarecsbatch)
        recctr = recctr + 1
        batchctr = batchctr + 1
        orarecs=[]
    if batchctr > 0:
        try:
            orcurr1.executemany(ora_inst_stmt9,orarecsbatch,batcherrors = True)
        except cx_Oracle.DatabaseError as e:
            errorObj, = e.args
            print("Error capturing FK Constraints")
            print(errorObj.message)
        orarecsbatch=[]
        batchctr = 0
        orarecs=[]
        #print("Captured ",recctr , " Triggers ")
        #print("Triggers: ",recctr )
        oraconn.commit()
pgcurr1.close()
orcurr1.close()

One response to “How to Insert/Update Data in Oracle Table from Postgresql query Using Python Script”

Leave a reply to How validate PostgreSQL vs Oracle Database table row counts for Data Validation Report after Initial/CDC Migration is completed | DBADEEDS Cancel reply