【问题标题】:Run SQL Query from Txt File Python从 Txt 文件 Python 运行 SQL 查询
【发布时间】:2020-11-20 08:17:59
【问题描述】:

您好,我正在尝试从文本文件加载一个巨大的查询(5000 多行),并使用下面的代码一次执行整个查询。如何从 txt 文件加载我的查询并使用 python pandas 执行它

我使用下面的代码打开了我的文本文件

query1 = open("Script.txt","r")

并尝试使用以下代码执行脚本。

df_ora1 = pd.read_sql(query1, con=connection1)

我收到以下错误

DatabaseError: sql '<_io.textiowrapper> 执行失败

我的文本文件有 """ 开始查询

结束查询 """

【问题讨论】:

  • 使用query1 = open("Script.txt","r").read()
  • 始终将 sql 查询存储在 .sql 文件中

标签: python-3.x pandas cx-oracle


【解决方案1】:
  1. 对于独立 - 我创建 sql,然后将其写入文件
  2. 您的解决方案 - 从文件中读取 sql。将其与连接一起传递给read_sql()
temptable = "tempx"
sql = f"""select Year, count(*) as c 
                        from {temptable} 
                        where Month=1 
                        and Sharpe between 1 and 2 
                        and stock like '%%2%%'
                        group by Year"""
with open("script.sql","w") as f: f.write(sql)
# read sql script from file.  pass it to pandas with connection
with open("script.sql") as f: sql = f.read()
engine = sqlalchemy.create_engine('mysql+pymysql://sniffer:sniffer@127.0.0.1/sniffer')
conn = engine.connect()
print(pd.read_sql(sql, conn).to_string(index=False))

输出

 Year    c
 2018  930
 2019  932
 2020  958

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    相关资源
    最近更新 更多