Search code examples
pythonattributeerrormysql-connector

AttributeError in Python MySQL Connector code. "No Attribute to self" after initialization


I'm encountering an AttributeError in my Python code using the MySQL Connector. I initialize my "mysql.connector.connect" and assign it to the variable "self.db_connection". When I try to call this variable inside another function in the same class I am receiving the following error:

    File "/Users/y.k./Desktop/MyProjects/Perosnal Coding projects/S_C.b/database/db_config.py", line 24, in get_connection
    print(self.db_connection)
AttributeError: 'connection' object has no attribute 'connection'. Did you mean: 'get_connection'?

This is my Code:

import mysql.connector
from mysql.connector import Error

class connection:

   def __init__(self):
       self.db_connection;
       try:
             self.db_connection = mysql.connector.connect(host='localhost', database='S-Cb_db', user='root', password='root')
             if self.db_connection.is_connected():
                   db_Info = self.db_connection.get_server_info()
                   print("Connected to MySQL Server version ",  db_Info)
                   cursor = self.db_connection.cursor()
                   cursor.execute("select database();")
                   record = cursor.fetchone()
                   print("You're connected to database: ", record)
       except Error as e:
             print("Error while connecting to MySQL", e)
        
   def get_connection(self):
       return self.db_connection;

For anyone asking why do I need this get connection function => First it's non of your business!!!

Second, and on a serious note, I am calling this function from another file "db_controller.py" and create a cursor from this connecting to execute queries.

I am curious to know what the issue is, and I hope it's not stupid. Thank you for any suggestions


Solution

  • Thank you for your answers, however, I found the issue, which is not caused by this file. The problem was the following: I run the code from the "main.py" file -> enter the "import db_controller.py" (a file responsible for handling the query executions) which does not have a constructor -> all the variables are created upon entering the file, hence calling for the connection from this given file before the initialization of the class and the connection.

    Hope this helps someone stuck and needs to look outside the box!