【问题标题】:How to convert SQL Oracle Database into a Pandas DataFrame?如何将 SQL Oracle 数据库转换为 Pandas DataFrame?
【发布时间】:2020-07-08 06:12:41
【问题描述】:

我正在尝试将 Oracle SQL 数据库导入 python,以便聚合/分析数据。 Pandas 对这项任务非常有用。但是每当我尝试使用我的代码时,它就会挂起并且不输出任何内容。我不确定是因为我使用的是 cx oracle 包,然后使用的是 pandas 包?

import cx_Oracle as cxo
import pandas as pd 
dsn=cxo.makedsn(
    'host.net',
    '1111',
    service_name='servicename'
)
conn=cxo.connect(
    user='Username',
    password='password',
    dsn=dsn)
c=conn.cursor()
a=c.execute("SELECT * FROM data WHERE date like '%20%'")
conn.close
df=pd.DataFrame(a)
head(df)

但是,当我使用下面的代码时,它会打印出我要查找的数据。我需要把这些数据转换成熊猫数据框,

for row in c: print(row)
conn.close()

我对 python 很陌生,所以非常感谢任何帮助!

【问题讨论】:

  • .read_sql() 有一个连接参数。 CX_Oracle - import data from Oracle to Pandas dataframe 显示它与cx_Oracle 连接一起使用。
  • 还有其他不同方法的答案,例如pd.DataFrame(cursor.fetchall()) - 搜索python pandas oracle sql 的变体
  • 这能回答你的问题吗? python-pandas and databases like mysql - cx_Oracle 有一个答案。
  • 正如 wwii 所说 - 您可以将查询直接传递给 read_sql 方法 - 即 pd.read_sql("SELECT * ... ", con = conn)
  • 当我尝试这样做时,程序只是挂起..

标签: python sql pandas oracle performance


【解决方案1】:

要将 cx_Oracle 游标转换为数据框,您可以使用以下代码。

with conn.cursor() as cursor:
    cursor.execute("SELECT * FROM data WHERE date like '%20%'")
    from pandas import DataFrame
    df = DataFrame(cursor.fetchall())
    df.columns = [x[0] for x in cursor.description]
    print("I got %d lines " % len(df))

注意我使用光标作为上下文管理器。所以它会在块结束时自动关闭。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-31
    • 2021-02-05
    • 2017-09-20
    • 2013-05-25
    • 2022-09-29
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    相关资源
    最近更新 更多