繁体   English   中英

Python TypeError中的Mysql.connector

[英]Mysql.connector in Python TypeError

我定义了一个数据库类,如下所示:

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

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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM