How to write pandas dataframe to oracle database using to_sql?
I've seen similar questions on SO - it happens when you try to write to Oracle DB using connection object created by cx_Oracle
.
Try to create connection using SQL Alchemy:
import cx_Oracle
from sqlalchemy import types, create_engine
conn = create_engine('oracle+cx_oracle://scott:tiger@host:1521/?service_name=hr')
df.to_sql('TEST', conn, if_exists='replace')
I am able to load an Oracle table using the following code:
import pandas as pd
import os
creds = {}
creds['tns_admin'] = 'Wallet_Path'
creds['sid'] = 'dev_low'
creds['user'] = 'username'
creds['password'] = pwd
os.environ['TNS_ADMIN'] = creds['tns_admin']
uri = 'oracle+cx_oracle://' + creds['user'] + ':' + creds['password'] + '@' + creds['sid']
df = pd.read_csv("test.csv")
df.to_sql('test', uri, schema='PRD', if_exists='replace')
Instead of connection we need to build and pass an URI.
Note: New Oracle databases (Autonomous) requires a wallet, so we need to set wallet path in TNS_ADMIN environment variable.
Also, I didn't have to import cx_Oracle, I did double check that
To ensure, I am not getting fooled, I dropped the table and did commit
And I executed above code, it created new table with data.