如何将 sql table 保存为 pandas 数据框?
How to save sql table as pandas dataframe?
我一直在尝试使用 cx_oracle 提取 sql table 并使用以下脚本将其保存为 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
pd.read_sql
的第一个参数应该是查询(如果我没记错的话)。您正在解析 cursor
object。尝试用 query
替换 pd.read_sql
中的 my_sql
即
pd.read_sql(query.format(id=id))
或使用光标object即
df = pd.DataFrame(my_sql.fetchall())
注意,fetchall()
仅 return 数据,即不是 header,可以使用 cursor.description
获得(参见 SO 答案 here )
我一直在尝试使用 cx_oracle 提取 sql table 并使用以下脚本将其保存为 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
pd.read_sql
的第一个参数应该是查询(如果我没记错的话)。您正在解析 cursor
object。尝试用 query
替换 pd.read_sql
中的 my_sql
即
pd.read_sql(query.format(id=id))
或使用光标object即
df = pd.DataFrame(my_sql.fetchall())
注意,fetchall()
仅 return 数据,即不是 header,可以使用 cursor.description
获得(参见 SO 答案 here )