Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save pandas (string/object) column as VARCHAR in Oracle DB instead of CLOB (default behaviour)

i am trying to transfer a dataframe to oracle database, but the transfer is taking too long, because the datatype of the variable is showing as clob in oracle. However i believe if i convert the datatype from clob to string of 9 digits with padded 0's , it will not take that much time. data is

product
000012320
000234234

is there a way to change the datatype of this variable to string of 9 digits. so that oracle does not think of it as CLOB object. i have tried the following.

df['product']=df['product'].astype(str)

or is there something else that might slow the transfer from python to oracle ?

like image 270
Mukul Avatar asked Sep 15 '16 06:09

Mukul


1 Answers

Here is a demo:

import cx_Oracle
from sqlalchemy import types, create_engine
engine = create_engine('oracle://user:password@host_or_scan_address:1521:ORACLE_SID')
#engine = create_engine('oracle://user:password@host_or_scan_address:1521/ORACLE_SERVICE_NAME')

In [32]: df
Out[32]:
           c_str  c_int   c_float
0        aaaaaaa      4  0.046531
1            bbb      6  0.987804
2  ccccccccccccc      7  0.931600

In [33]: df.to_sql('test', engine, index_label='id', if_exists='replace')

In Oracle DB:

SQL> desc test
 Name                Null?    Type
 ------------------- -------- -------------
 ID                           NUMBER(19)
 C_STR                        CLOB
 C_INT                        NUMBER(38)
 C_FLOAT                      FLOAT(126)

now let's specify an SQLAlchemy dtype: 'VARCHAR(max_length_of_C_STR_column)':

In [41]: df.c_str.str.len().max()
Out[41]: 13

In [42]: df.to_sql('test', engine, index_label='id', if_exists='replace',
   ....:           dtype={'c_str': types.VARCHAR(df.c_str.str.len().max())})

In Oracle DB:

SQL> desc test
 Name            Null?    Type
 --------------- -------- -------------------
 ID                       NUMBER(19)
 C_STR                    VARCHAR2(13 CHAR)
 C_INT                    NUMBER(38)
 C_FLOAT                  FLOAT(126)

PS for padding your string with 0's please check @piRSquared's answer

like image 108
MaxU - stop WAR against UA Avatar answered Nov 16 '22 20:11

MaxU - stop WAR against UA