【问题标题】:Mysql.connector in Python TypeErrorPython TypeError 中的 Mysql.connector
【发布时间】:2018-06-18 17:26:46
【问题描述】:

我已经定义了一个数据库类如下:-

class Database(object):
    """ Implements all interactions with the DB. """

    def __init__(self, id_a, id_b, config):
        self.config = config
        self.id_a = id_a
        self.id_b = id_b
        self.db_connection = None
        self.cursor = None
        self.__init_db(config)

    def __init_db(self, config):
        """
        Initializes the MySQL Connector using the settings
        specified in the system configuration.

        """
        self.db_connection = mysql.connector.connect(user=config['database_user'],
                                                     password=config['database_password'],
                                                     host=config['database_host'],
                                                     database=config['database_name'])
        self.cursor = self.db_connection.cursor(dictionary=True,buffered=True)
        self.cursor.execute('SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;')

现在,当我定义以下函数以返回从 Mysql 数据库中获取的值时,我得到一个错误

    def get_func(self):
        sql = "SELECT c_id FROM table \
        WHERE id_a = {} ".format(self.id_a)
        self.cursor.execute(sql)
        rows = self.cursor.fetchone()
        if rows:
            for row in rows:
                ls1 = row['id_number']
            return ls1



    ls1 = row['id_number']
TypeError: string indices must be integers

【问题讨论】:

    标签: python string python-2.7 byte mysql-python


    【解决方案1】:

    row['id_number'] row 中不是dict 类型,而是tuple 类型。

    for row in rows:
        ls1 = row['id_number'] # error
    

    你的情况是这样的

    words = ('foo',)
    words['id_number'] # error we need to pass only `int`
    
    words[0] # right
    # Output
    # foo
    

    row 也是单身,您不需要使用 for loop statment 只需 row[0]

    row = self.cursor.fetchone()
    if row:
        return row[0]
    

    【讨论】:

    • 我可以做一个row = self.cursor.fetchall() 并使用dict类型
    • 为什么需要字典类型?如果您从 table 中仅选择 c_id 并仅使用 fetchone() 简单返回 row[0] 就可以了
    猜你喜欢
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 2021-08-07
    • 2017-05-11
    相关资源
    最近更新 更多