【问题标题】:Python mysql error with cursor带有光标的Python mysql错误
【发布时间】: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 脚本?

标签: python mysql


【解决方案1】:

所以...经过一些故障排除...

解决方案是从配置文件所在文件夹外部调用脚本时set the current working directory

【讨论】:

  • 是的,它通常是最难找到的最简单的东西。
【解决方案2】:

我已经从 read_db_config 运行了您的代码,一切正常。 我认为问题在于配置文件的路径。 如果您只是从应用程序的根路径开始,我的意思是:

- root_dir
    - parser.py
    - config.ini

您的函数可以正常运行,但是当您作为导入的库运行时,您需要将整个路径传递给该函数。

>>import os
>>parser = ConfigParser()
>>parser.read(os.path.abspath('<abs_path_of_config_file>')

【讨论】:

    猜你喜欢
    • 2016-08-20
    • 1970-01-01
    • 2013-03-28
    • 2018-07-12
    • 1970-01-01
    • 2019-01-06
    • 2013-10-02
    • 1970-01-01
    • 2013-01-26
    相关资源
    最近更新 更多