【问题标题】:Run sql query which is saved in text file using python使用python运行保存在文本文件中的sql查询
【发布时间】:2019-04-23 12:49:19
【问题描述】:

我在 .txt 文件中有查询,我正在尝试使用 python 运行该查询。如果我的查询用单行编写,它工作正常。但我的查询在文本文件中有多行。它给出了语法错误,因为它只读取第一行。

我试过下面的代码

cursor = cnxn.cursor()
with open('C:\Python_Script_Test\INSERTS.txt','r') as inserts:
    for statement in inserts:
        cursor.execute(statement)

我有大查询,其中包含多行。您能否建议最好的代码来阅读所有行来运行查询。

【问题讨论】:

标签: python


【解决方案1】:

尝试使用.read()

例如:

cursor = cnxn.cursor()
with open('C:\Python_Script_Test\INSERTS.txt','r') as inserts:
    query = inserts.read()
cursor.execute(query)

【讨论】:

    【解决方案2】:

    .read() 适用于单行查询。对于多行查询,Python 创建行列表。您可以使用 .append() 将行整理在一起,但您需要在每行的末尾添加 SQL 服务器可读的 CRLF 标记...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-20
      • 1970-01-01
      • 2021-11-24
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多