运行使用python保存在文本文件中的sql查询

问题描述 投票:1回答:2

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

我试过下面的代码

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

我有大量查询,其中包含多行。你可以建议最好的代码来读取所有运行查询的行。

python
2个回答
0
投票

尝试使用.read()

例如:

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.