简体   繁体   中英

Mysql.connector in Python TypeError

I have defined a Database class as follows:-

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;')

Now, when i define the below function to return the values fetched from the Mysql database i get an error

    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

in row['id_number'] row is not a of type dict , but is of type tuple .

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

in your case you do something like this

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

words[0] # right
# Output
# foo

also the row is single you don't need to use for loop statment just row[0]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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