gpt4 book ai didi

python - 在 Oracle DB 中将 pandas(字符串/对象)列保存为 VARCHAR 而不是 CLOB(默认行为)

转载 作者:太空狗 更新时间:2023-10-30 02:41:23 24 4
gpt4 key购买 nike

我正在尝试将数据帧传输到 oracle 数据库,但传输时间太长,因为变量的数据类型在 oracle 中显示为 clob。但是我相信,如果我将数据类型从 clob 转换为 9 位数字 并用填充 0,它不会花费那么多时间。数据是

product
000012320
000234234

有没有办法将此变量的数据类型更改为 9 位数字的字符串。这样 oracle 就不会将其视为 CLOB 对象。我尝试了以下方法。

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

或者是否有其他因素可能会减慢从 python 到 oracle 的传输速度?

最佳答案

这是一个演示:

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')

在 Oracle 数据库中:

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

现在让我们指定一个 SQLAlchemy 数据类型:'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())})

在 Oracle 数据库中:

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

关于用 0 填充字符串的 PS,请检查 @piRSquared's answer

关于python - 在 Oracle DB 中将 pandas(字符串/对象)列保存为 VARCHAR 而不是 CLOB(默认行为),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39504351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com