【问题标题】:How to save sql table as pandas dataframe?如何将 sql 表保存为 pandas 数据框?
【发布时间】:2026-01-22 16:05:01
【问题描述】:

我一直在尝试使用 cx_oracle 提取 sql 表并使用以下脚本将其保存为 pandas 数据框:

import  cx_Oracle
import pandas as pd

id = 1234
connection = cx_Oracle.connect(user="user", password='pwd',dsn="dsn")
# Obtain a cursor
cursor = connection.cursor()
# Execute the query
query = """select * from table where id= {id}"""
my_sql =cursor.execute(query.format(id=id))
df_sql = pd.read_sql(my_sql, connection)

我能够连接到数据库,但无法将其保存为 pandas 数据框。我怎么做?我收到以下错误:

  File "file/to/path.py", line 38, in file
    df_sql = pd.read_sql(my_sql, connection)
  File "C:\file/to/path\venv\lib\site-packages\pandas\io\sql.py", line 495, in read_sql
    return pandas_sql.read_query(
  File "File/to/path\venv\lib\site-packages\pandas\io\sql.py", line 1771, in read_query
    cursor = self.execute(*args)
  File "File/to/path\venv\lib\site-packages\pandas\io\sql.py", line 1737, in execute
    raise ex from exc
pandas.io.sql.DatabaseError: Execution failed on sql '<cx_Oracle.Cursor on <cx_Oracle.Connection to dsn>>': expecting string or bytes object

【问题讨论】:

  • 你能发布完整的堆栈跟踪吗?看起来像是连接/查询问题。
  • 更新了错误信息
  • 我已将其添加为 aswer(请在答案中评论,您使用了哪一个,哪个有效)
  • 不要这样做query = """select * from table where id= {id}""",因为这会使您面临 SQL 注入安全攻击,并且还会影响性能和可伸缩性。使用绑定变量,见*.com/a/51790579/4799035

标签: python sql pandas cx-oracle


【解决方案1】:

pd.read_sql 的第一个参数应该是查询(如果我没记错的话)。您正在解析 cursor 对象。尝试将pd.read_sql 中的my_sql 替换为query,即

pd.read_sql(query.format(id=id))

或使用光标对象,即

df = pd.DataFrame(my_sql.fetchall())

注意,fetchall() 只返回数据,即不返回标头,可以使用 cursor.description 获得(参见 SO 答案 here

【讨论】:

  • 我使用了pd.read_sql(query.format(id=id)),它成功了!感谢您的帮助
最近更新 更多