Python - 从文件执行多个SQL查询

时间:2017-05-02 00:19:16

标签: sql sql-server python-2.7 pymssql

我正在尝试从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 

1 个答案:

答案 0 :(得分:0)

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

for command in sqlCommands:

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