Python MySQL Connector初始化后遇AttributeError:connection对象无对应属性
MySQL Connector Python代码中AttributeError问题排查与解决
问题重现
运行Python代码使用MySQL Connector时触发AttributeError,错误日志如下:
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;
需要通过get_connection函数在db_controller.py中获取连接并创建游标执行查询。
问题原因
- 命名冲突导致混淆:自定义类名
connection与mysql.connector.connect()返回的连接对象类名完全一致,容易在调用时产生混淆,误写属性名。 - 调用代码存在错误:错误日志提示
'connection' object has no attribute 'connection',说明你在db_controller.py中调用时,错误地尝试访问实例的connection属性(比如写成conn.connection),但你的类实例并没有这个属性,正确的应该是调用get_connection()方法或者访问db_connection属性。 - 初始化代码有无效语句:
__init__方法中的self.db_connection;是无意义的空语句,虽然不会直接引发错误,但属于冗余代码。
解决建议
1. 重命名自定义类,避免命名冲突
将自定义类名改为DBConnection这类更清晰、不会与内置类重名的名称,减少混淆概率:
import mysql.connector from mysql.connector import Error class DBConnection: # 修改类名 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) self.db_connection = None # 连接失败时显式赋值为None,避免后续调用报错 def get_connection(self): return self.db_connection
2. 修正db_controller.py中的调用代码
确保正确调用get_connection()方法获取连接:
from db_config import DBConnection # 对应修改后的类名 # 创建连接实例 db_conn = DBConnection() # 获取连接对象 connection = db_conn.get_connection() # 检查连接是否有效后创建游标执行查询 if connection: cursor = connection.cursor() cursor.execute("SELECT * FROM your_table") results = cursor.fetchall() # 处理查询结果 cursor.close()
3. 优化连接失败的处理逻辑
在__init__的异常捕获中,给self.db_connection赋值为None,这样后续调用get_connection()时可以判断连接是否成功,避免出现新的属性错误。
内容的提问来源于stack exchange,提问作者Youssof. K.
相关产品推荐
相关产品推荐

