【问题标题】:Python - Execute multiple SQL query from filePython - 从文件执行多个 SQL 查询
【发布时间】:2017-05-02 00:19:16
【问题描述】:

我正在尝试从 Python 2.7.13 中的文件执行 SQL 查询,并在显示结果集时收到以下错误。 文件中的 SQL 语句很简单,例如 count(*) from table,但如果这个逻辑有效,我需要用复杂的查询替换它。

错误

Info : (7,)
Traceback (most recent call last):
  File "SQLserver_loop.py", line 19, in <module>
    fields = c.fetchall()
  File "pymssql.pyx", line 542, in pymssql.Cursor.fetchall (pymssql.c:9352)
pymssql.OperationalError: Statement not executed or executed statement has no re
sultset 

Python 脚本:

import pymssql

conn = pymssql.connect(
    host=r'name',
    user=r'user',
    password='credential',
    database='Test')

c = conn.cursor()


fd = open('ZooDatabase.sql', 'r')     # Open and read the file as a single buffer

sqlFile = fd.read()

fd.close()


sqlCommands = sqlFile.split(';')        # all SQL commands (split on ';')


for command in sqlCommands:         # Execute every command from the input file

     c.execute(command)

     fields = c.fetchall()

     for row in fields:

      print "Info : %s " % str(row)

c.close()

conn.close()   

错误信息

    **SQL File - ZooDatabase.sql**

    select count(*) from emp2;

    select count(*) from emp1; 

**Error Log with SQL print statement output:**

   C:\Python27\pycode>python SQLserver_loop.py
    SELECT count(*) FROM emp2
    Info : (7,)

    SELECT count(*) FROM emp1
    Info : (7,)

    Traceback (most recent call last):
      File "SQLserver_loop.py", line 20, in <module>
        fields = c.fetchall()
      File "pymssql.pyx", line 542, in pymssql.Cursor.fetchall (pymssql.c:9352)
    pymssql.OperationalError: Statement not executed or executed statement has no re
    sultset 

【问题讨论】:

  • 检查文件中查询的格式。将其添加到问题中。
  • 让您的代码在执行查询时显示查询,以便您知道是哪个查询导致了问题,然后edit您的问题向我们展示该查询的样子。
  • 在问题中添加了SQL文件和打印语句的请求信息。
  • 嗯,为了看到失败的command,你需要print之前你尝试execute它。
  • 这就是我打印的方式,即在执行 SQL 之前,看起来查询是按顺序执行的,但请注意,因为 SQL 计数输出显示为“信息:(7,)”格式,即使用 c.fetchall() 时导致上述错误?

标签: sql sql-server python-2.7 pymssql


【解决方案1】:

fields = c.fetchall() 导致我评论它的错误并且现在可以正常工作。

for command in sqlCommands:

     #print command
     c.execute(command)
     #fields = c.fetchall()
     for row in c:
      print (row) 

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 1970-01-01
    • 2020-11-20
    相关资源
    最近更新 更多