Why “name 'cursor' is not defined” when pyodbc cursor is in main()?
本问题已经有最佳答案,请猛点这里访问。
我在命令行运行一个下面浓缩的python程序,它给了我一个错误(
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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() |
您在未定义
当您在
尝试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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。
因为在
解决此问题的最佳方法可能是将光标对象传递给