当pyodbc游标在main()中时,为什么没有“命名'游标''?

时间:2015-08-21 20:02:21

标签: python pyodbc

我正在从命令行运行一个Python程序,在下面压缩,它给我一个错误(name 'cursor' is not defined)并指向底部附近的cursor.fetchmany()行。但是,如果我将main()的前两行,conncursor分配在main()之上和之外移动到程序正文中,程序将按需运行。当我在cursor内分配main()时,为什么这不起作用?我很想知道这是否只是pyodbc库的一个怪癖,或者有更好的方法让它从main()内部开始工作,或者实际上可以将分配留在程序体内

import pyodbc
import csv
#   ...other modules...

def main():
    conn = pyodbc.connect(DSN=abcxyz, autocommit=True)
    cursor = conn.cursor()
#   ...sys.argv assignments and validation...
    pull_data(query_file, start_date, end_date, out_file)

def pull_data(query_file, start_date, end_date, out_file):
#   ...prepare query as string, date range as list...
    for date in list_dates:
        cursor.execute(query, date)
        append_rows(out_file)

def append_rows(out_file):
    with open(out_file, 'a', newline='') as file:
        writer = csv.writer(file)
        while True:
            results = cursor.fetchmany(chunk_size)
            if not results:
                break
            for result in results:
                writer.writerow(result)

if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:2)

因为游标未在append_rows()pull_data()中定义。您已在main()中对其进行定义,因此只能在main()中访问。

解决此问题的最佳方法可能是将光标对象传递给append_rows()pull_data()

答案 1 :(得分:2)

您在cursor未被定义的情况下收到错误的原因是因为它在您的函数中不存在。变量仅存在于它们定义的范围内。

当您在cursor之外定义main时,它被声明为全局变量,这意味着它可以在脚本的所有范围内访问。

尝试:

import pyodbc
import csv
#   ...other modules...

def main():
    # Since conn and cursor are being declared here, they only exist within the scope of this function, not other functions that are called.
    conn = pyodbc.connect(DSN=abcxyz, autocommit=True)
    cursor = conn.cursor()
#   ...sys.argv assignments and validation...
    # make sure we give the cursor to pull_data so it will exist in its scope!
    pull_data(query_file, start_date, end_date, out_file, cursor)

def pull_data(query_file, start_date, end_date, out_file, cursor):
#   ...prepare query as string, date range as list...
    for date in list_dates:
        cursor.execute(query, date)
        # Pass the cursor to append_rows
        append_rows(out_file, cursor)

# cursor is actually passed to the append_rows function. Now it exists in this scope
def append_rows(out_file, cursor):
    with open(out_file, 'a', newline='') as file:
        writer = csv.writer(file)
        while True:
            results = cursor.fetchall()
            for result in results:
                writer.writerow(result)

if __name__ == '__main__':
    main()

我还建议您阅读https://stackoverflow.com/a/292502/5249060