You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Polars与cx_Oracle读取SQL查询时出现错误

解决Polars读取cx_Oracle连接时的'split'属性错误

问题场景

使用cx_Oracle建立Oracle数据库连接后,直接将连接对象传入Polars的ps.read_database()方法执行SQL查询,触发错误:

'cx_Oracle.Connection' object has no attribute 'split'

错误原因

Polars的read_database方法并不直接支持传入原生cx_Oracle连接对象,底层会误将该连接对象当作字符串处理(尝试调用split方法解析连接信息),因此抛出属性不存在的错误。

解决方案

方案一:通过SQLAlchemy引擎连接

借助SQLAlchemy构建符合Polars要求的数据库引擎,代码简洁且适配Polars原生方法:

import polars as ps
from sqlalchemy import create_engine

# 替换为实际数据库信息
user = "XXX"
host = "XXX"
port = "XXX"
service_name = "XXX"
password = "XXX"

# 构建SQLAlchemy兼容的Oracle连接字符串
conn_str = f"oracle+cx_oracle://{user}:{password}@{host}:{port}/?service_name={service_name}"

# 创建数据库引擎
engine = create_engine(conn_str)

# 执行查询并读取结果
query = "XXX"  # 替换为实际SQL查询语句
result = ps.read_database(query, engine)

方案二:用cx_Oracle原生API读取后转Polars DataFrame

无需额外依赖SQLAlchemy,直接通过cx_Oracle游标获取数据,再转换为Polars DataFrame:

import polars as ps
import cx_Oracle as oracle

# 替换为实际数据库信息
user = "XXX"
host = "XXX"
port = "XXX"
service_name = "XXX"
password = "XXX"

# 建立cx_Oracle连接
dsnStr = oracle.makedsn(host, port, service_name)
gds_con = oracle.connect(user, password, dsnStr)

query = "XXX"  # 替换为实际SQL查询语句

# 执行查询并获取数据
cursor = gds_con.cursor()
cursor.execute(query)

# 提取列名和数据
columns = [desc[0] for desc in cursor.description]
data = cursor.fetchall()

# 转换为Polars DataFrame
result = ps.DataFrame(data, columns=columns)

# 关闭资源
cursor.close()
gds_con.close()

内容的提问来源于stack exchange,提问作者JBosmans

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 09:20:09