Python TypeError中的Mysql.connector

时间:2018-06-18 17:26:46

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

我已经按如下方式定义了一个Database类: -

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

1 个答案:

答案 0 :(得分:0)

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]