尝试从 class 内部而不是外部获取游标时获取 MySQL 连接不可用
Getting MySQL Connection not available when trying to get a cursor from inside a class but not from outside
我在 OS X 10.9 上 运行 mariadb 数据库并尝试通过 python.
连接到它
如果我尝试此代码,它运行良好
import mysql.connector as mariadb
if __name__ == "__main__":
mariadb_connection = mariadb.connect(user='root', database='account_balances')
cursor = mariadb_connection.cursor()
我可以事件插入一些记录
但如果我尝试以下
class account(object):
_logging_to_db_enabled = False
_database_object = None
_database_cursor = None
def __init__(self):
pass
def enable_logging_to_db(self):
try:
self._database_object = mariadb.connect(mariadb.connect(user='root', database='account_balances'))
self._logging_to_db_enabled = True
except self._database_object.Error as error:
print ("Opening DB error: {}".format(error))
self._database_cursor = self._database_object.cursor()
if __name__ == "__main__":
testobject = account()
testobject.enable_logging_to_db()
我收到这个错误
File "....", line 22, in enable_logging_to_db
self._database_cursor = self._database_object.cursor()
File "<pathname_deleted>", line 1372, in cursor
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
有人知道为什么这在 main 中有效但在对象中无效吗?
因为你有typo/copy&粘贴错误:
self._database_object = mariadb.connect(mariadb.connect(user='root', database='account_balances'))
应该是:
self._database_object = mariadb.connect(user='root', database='account_balances')
我在 OS X 10.9 上 运行 mariadb 数据库并尝试通过 python.
连接到它如果我尝试此代码,它运行良好
import mysql.connector as mariadb
if __name__ == "__main__":
mariadb_connection = mariadb.connect(user='root', database='account_balances')
cursor = mariadb_connection.cursor()
我可以事件插入一些记录
但如果我尝试以下
class account(object):
_logging_to_db_enabled = False
_database_object = None
_database_cursor = None
def __init__(self):
pass
def enable_logging_to_db(self):
try:
self._database_object = mariadb.connect(mariadb.connect(user='root', database='account_balances'))
self._logging_to_db_enabled = True
except self._database_object.Error as error:
print ("Opening DB error: {}".format(error))
self._database_cursor = self._database_object.cursor()
if __name__ == "__main__":
testobject = account()
testobject.enable_logging_to_db()
我收到这个错误
File "....", line 22, in enable_logging_to_db
self._database_cursor = self._database_object.cursor()
File "<pathname_deleted>", line 1372, in cursor
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
有人知道为什么这在 main 中有效但在对象中无效吗?
因为你有typo/copy&粘贴错误:
self._database_object = mariadb.connect(mariadb.connect(user='root', database='account_balances'))
应该是:
self._database_object = mariadb.connect(user='root', database='account_balances')