Skip to content
Advertisement

‘NoneType’ has not attribute (using pyodbc/sql connection)

Wondering why Python returns 'NoneType' object has no attribute 'connection' using the code below. I believe I’ve properly created the self.connection variable within the class, but attempting to call it using an instance returns the above error. Is the connection somehow terminated before I can retrieve the connection attribute?

import pyodbc

class sql:
    
    def __init__(self):
        
        self.driver = "{ODBC Driver 17 for SQL Server}"
        self.server = ".SQLEXPRESS"
        self.database = "lotto"
        self.trusted_connection = "YES"
        self.mars_connection = "YES"

    def sql_conn(self):
        
        """Connect to local SQL Server"""
        
        print('nConnecting to SQL Server...')
    
        self.connection = pyodbc.connect(
            'DRIVER=' + self.driver
            + ';SERVER=' + self.server
            + ';DATABASE=' + self.database
            + ';Trusted_Connection=' + self.trusted_connection
            + ';MARS_CONNECTION=' + self.mars_connection
        )

        print(self.connection)
        self.cursor = self.connection.cursor()
        
        print('nConnection to SQL Server established.')

sql_instance = sql()
conn = sql_instance.sql_conn().connection

Advertisement

Answer

sql_conn() doesn’t explicitly return anything, so it implicitly returns None.

One way to solve this issue without changing your methods is to split the last line into two lines – one for initializing the connection and the other one for retrieving it:

sql_instance = sql()
sql_instance.sql_conn()
conn = sql_instance.connection
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement