Skip to content
Advertisement

Unable to use ‘read_sql’ to call a SQL query class

I am trying to pull results from the database with the following code:

import pandas as pd
import pyodbc

class DataManagement(object):

    def __init__(self, database = None, server=None, trusted_connection=True, database_driver=ODBC_SQL2005_2012, uid=None, pwd=None):
        self.server = server
        self.database = database
        self.uid = uid
        self.pwd = pwd

        
        # Use default server name none supplied - assumed to be localhost
        if self.server is None:
            self.server = SERVER

        if self.database is None:
            self.database = DATABASE

        # Use default sql credentials if none provided
        if self.uid is None or self.pwd is None:
            self.uid = DEFAULT_UID
            self.pwd = DEFAULT_PASSWORD

        if trusted_connection:
            self.connectionstring = "DRIVER={0};SERVER={1};DATABASE={2};Trusted_Connection=yes;".format(database_driver, self.server, self.database)
        else:
            self.connectionstring = 'DRIVER={0};SERVER={1};DATABASE={2};UID={3};PWD={4};'.format(database_driver, self.server, self.database, uid, pwd)

        self.connection = pyodbc.connect(self.connectionstring)
        
        self.cursor = self.connection.cursor()

    def __enter__(self):
        return self

    def __exit__(self, ctx_type, ctx_value, ctx_traceback):
        self.connection.commit()
        self.connection.close()

qq = DataManagement()
sql =("select * from ***** ")
data_df = pd.read_sql(sql, qq)

I get an error:

Traceback (most recent call last):

  File "<ipython-input-94-453876631fe0>", line 3, in <module>
    data_df = pd.read_sql(sql, qq)

  File "***AppDataLocalContinuumanaconda3libsite-packagespandasiosql.py", line 380, in read_sql
    chunksize=chunksize)

  File "***AppDataLocalContinuumanaconda3libsite-packagespandasiosql.py", line 1468, in read_query
    cursor = self.execute(*args)

  File "***AppDataLocalContinuumanaconda3libsite-packagespandasiosql.py", line 1426, in execute
    cur = self.con.cursor()

TypeError: 'pyodbc.Cursor' object is not callable

I saw a similar question at TypeError: ‘pyodbc.Cursor’ object is not callable (Python 3.6) but unable to get an answer from there.

Advertisement

Answer

I got it to work by editing the class from

self.cursor = self.connection.cursor()

into

self.cursor = self.connection.cursor
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement