AttributeError。初始化后“无自我属性”

问题描述 投票:0回答:1

我在使用 MySQL 连接器的 Python 代码中遇到了 AttributeError。我初始化“mysql.connector.connect”并将其分配给变量“self.db_connection”。 当我尝试在同一个类的另一个函数中调用此变量时,我收到以下错误:

    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'?

这是我的代码:

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;

对于任何问我为什么需要这个获取连接功能的人 => 首先,这不关你的事!!!

其次,严肃地说,我从另一个文件“db_controller.py”调用此函数,并从此连接创建一个游标来执行查询。

我很想知道问题是什么,希望这不是愚蠢的。 谢谢大家的建议

python attributeerror mysql-connector
1个回答
0
投票
import mysql.connector
from mysql.connector import Error

class connection:
   def __init__(self): 
      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

您好,快速修复。

© www.soinside.com 2019 - 2024. All rights reserved.