Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/visual-studio/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python运行保存在文本文件中的sql查询_Python - Fatal编程技术网

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

使用python运行保存在文本文件中的sql查询,python,Python,我在.txt文件中有一个查询,我正在尝试使用python运行该查询。如果我的查询是用单行写的,那么它可以正常工作。但我的查询在文本文件中有多行。它给出了语法错误,因为它只读取第一行 我试过下面的代码 cursor = cnxn.cursor() with open('C:\Python_Script_Test\INSERTS.txt','r') as inserts: for statement in inserts: cursor.execute(statement)

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

我试过下面的代码

cursor = cnxn.cursor()
with open('C:\Python_Script_Test\INSERTS.txt','r') as inserts:
    for statement in inserts:
        cursor.execute(statement)
我有一个包含多行的大查询。您可以建议最好的代码来读取所有要运行查询的行。

尝试使用
.read()

Ex:

cursor = cnxn.cursor()
with open('C:\Python_Script_Test\INSERTS.txt','r') as inserts:
    query = inserts.read()
cursor.execute(query)
.read()用于单行查询。对于多行查询,Python创建行列表。您可以使用.append()将行整理在一起,但需要在SQL server可读的每行末尾添加CRLF标记…

是否尝试过?这可能对你有帮助。