TypeError: 'pyodbc.Cursor' object is not callable (Python 3.6)

余生长醉 提交于 2021-02-10 16:42:54

问题


I'm connecting to a database and trying to run an MS SQL query whose result is saved as a CSV file. When I try to execute my code, it's returning this error:

Traceback (most recent call last):
  File "C:\Users\aubrey_s\PycharmProjects\Drawings_Converter\src\DrawingsConverter.py", line 220, in <module>
    main()
  File "C:\Users\aubrey_s\PycharmProjects\Drawings_Converter\src\DrawingsConverter.py", line 202, in main
    db_conn.retrieve_part_list()
  File "C:\Users\aubrey_s\PycharmProjects\Drawings_Converter\src\DrawingsConverter.py", line 40, in retrieve_part_list
    WHERE [DRAWING_FILE] IS NOT NULL''')
  File "C:\Users\aubrey_s\PycharmProjects\Drawings_Converter\src\DrawingsConverter.py", line 32, in execute
    self.cursor('{}'.format(query))
TypeError: 'pyodbc.Cursor' object is not callable

This is the code I'm running:

import csv
import logging
import pyodbc

class DatabaseConnector:
        """"Used to establish connection to a given database and perform queries\""""

    def __init__(self):
        self.dbConn = None
        self.cursor = None
        self.data = None

    def connect_to(self, host, user, password, database):
        try:
            self.dbConn = pyodbc.connect('DRIVER={};SERVER={};DATABASE={};UID={};PWD={}'.format(
                '{SQL Server}', host, database, user, password))

            logging.info("Connected to {} on port {}".format(host, port))

            self.cursor = self.dbConn.cursor()
        except ConnectionError:
            logging.critical("Could not establish a connection to {} on port {}".format(host, port))

    def execute(self, query):
        self.cursor('{}'.format(query))
        self.data = self.cursor.fetchall()
        logging.info("Executed: {}".format(query))

    def retrieve_part_list(self):
        self.execute('''SELECT ALL [DRAWING_FILE],
                                [USER_1]
                        FROM [TRAINING].[dbo].[PART] 
                        WHERE [DRAWING_FILE] IS NOT NULL''')

        with open('part_reference_list.csv', newline='') as csvfile:
            line_writer = csv.writer(csvfile, delimiter=',')
            for row in self.data:
                line_writer.writerow(row)

def main():
    # Clear contents of log file from previous executions
    logfile = open('log.log', 'r+')
    logfile.truncate(0)
    logfile.close()

    # Define logging parameters
    logging.basicConfig(filename='log.log',
                        format='%(asctime)s - %(levelname)s - %(filename)s - %(message)s',
                        level=logging.INFO)
    logging.info("Main is running...")

    # Attempt to connect to the database
    # and retrieve the latest part reference list
    db_conn = DatabaseConnector()
    db_conn.connect_to(host="an-visual",
                       user="admin",
                       password="adminpass",
                       database="TRAINING")
    db_conn.retrieve_part_list()

if __name__ == '__main__':
    main()

Can anyone provide any insight to what's going on? Why is the error being thrown? What steps can I do to resolve it? How can I avoid errors like this in the future?

I'm still learning python so any info that could help further my knowledge would be greatly appreciated!

来源:https://stackoverflow.com/questions/44572809/typeerror-pyodbc-cursor-object-is-not-callable-python-3-6

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!