【发布时间】:2016-10-16 16:18:14
【问题描述】:
您好,当我尝试连接到 mysql 数据库时出现错误。
import threading
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
class Queue (threading.Thread):
def __init__(self, threadID, lock):
threading.Thread.__init__(self)
self.threadID = threadID
self.lock = lock
def run(self):
while True:
try:
dbconfig = read_db_config()
conn = MySQLConnection(**dbconfig)
cursor = conn.cursor()
except Error as e:
print(e)
finally:
cursor.close()
conn.close()
这是代码的条纹部分,但我仍然在finally: 之后的行上遇到相同的错误,它说cursor 未定义。
该代码在 Ubuntu 上的守护程序中运行。
编辑:
有关代码的更多信息
read_db_config()
from configparser import ConfigParser
def read_db_config(filename='config.ini', section='mysql'):
""" Read database configuration file and return a dictionary object
:param filename: name of the configuration file
:param section: section of database configuration
:return: a dictionary of database parameters
"""
# create parser and read ini configuration file
parser = ConfigParser()
parser.read(filename)
# get section, default to mysql
db = {}
if parser.has_section(section):
items = parser.items(section)
for item in items:
db[item[0]] = item[1]
else:
raise Exception('{0} not found in the {1} file'.format(section, filename))
return db
还有错误值的配置文件
[mysql]
host = IP
database = database
user = user
password = password
编辑2: 在没有 try 语句的情况下运行代码会出现此错误
mysql not found in the config.ini file
可能是我的 read_db_config() 函数找不到配置文件,但它们在同一个文件夹中。
【问题讨论】:
-
如果您在
cursor = conn.cursor()行之前遇到异常,那么 cursor.close() 可能会失败... -
Okej 所以很可能
conn = MySQLConnection(**dbconfig)是错误的。 -
删除try语句后出现新错误。
mysql not found in the config.ini file -
发现错误知道我在文件夹外时调用了 python 脚本。但是有没有办法避免这个错误,所以我可以在文件夹外调用 python 脚本?
-
试试
os.chdir-- docs.python.org/library/os.html#os.chdir