python读取CLOB数据

时间:2019-06-11 19:30:24

标签: python oracle

我正在尝试从具有一个CLOB列的Oracle表中读取数据。我可以用数据创建一个数据框,但必须保持与数据库的连接。

df = pd.read_sql("""
select 
COURSE_NUMB,
COURSE_DESCRIPTION
from COURSE_DATA
""",conn)

df.head(1)

COURSE_NUMB   COURSE_DESCRIPTION
1             Lorem ipsum dolor sit amet, consectetur....

关闭与数据库的连接后,CLOB数据不再可用。

conn.close()
df.head()

DatabaseError: DPI-1040: LOB was already closed

我尝试制作数据框的副本或将其导出到json文件,但是在复制或导出中仍然缺少CLOB数据。

1 个答案:

答案 0 :(得分:1)

我们必须在CLOB对象上调用read()才能将其值读入DataFrame:

### Set up table with CLOB data
SQL> DESC course_data
Name               Null? Type   
------------------ ----- ------ 
COURSE_NUMB              NUMBER 
COURSE_DESCRIPTION       CLOB   

SQL> SELECT * FROM course_data;

COURSE_NUMB COURSE_DESCRIPTION                                                              
----------- -------------------------------------------
          1 Lorem ipsum dolor sit amet, consectetur....   

### Python code
df = pd.DataFrame()

cursor = conn.cursor()
cursor.execute(""" select COURSE_NUMB, COURSE_DESCRIPTION from COURSE_DATA """)

for row in cursor:
  # row[0] = COURSE_NUMB
  # row[1] = COURSE_DESCRIPTION - note the call to "read()" on the CLOB
  df_tmp = pd.DataFrame([[row[0], row[1].read()]],
                        columns=["COURSE_NUMB", "COURSE_DESCRIPTION"])
  df = df.append(df_tmp, ignore_index=True)

print ("***Before conn.close()")
print(df.head(1))
conn.close()
print ("\n***After conn.close()")
print(df.head())

### Output
$ python test.py
***Before conn.close()
   COURSE_NUMB                           COURSE_DESCRIPTION
0            1  Lorem ipsum dolor sit amet, consectetur....

***After conn.close()
   COURSE_NUMB                           COURSE_DESCRIPTION
0            1  Lorem ipsum dolor sit amet, consectetur....