2

I m looking for a default fetch object Cursor method for my select queries, I m using this code permanently to fetch all received data from my cursor.

My implementation of fetch object method

def fetch_object(self,cursor):
    data = cursor.fetchall()
    names = cursor.column_names
    results = []
    for info in data:
        object = {}
        for index in range(len(names)):
            object[names[index]] = info[index]
        results.append(object)
    return results

My selecting data code and fetching

 try:
        cursor = self.connexion.cursor()
        cursor.execute("SELECT * FROM domains")
        domains = self.fetch_object(cursor)
        return domains
    except Error as error:
        print(error)

Any other suggestion way ( a exists way in mysql:connector fetch methods ) with mysql:connector,thank you.

1 Answers1

3

You can use cursor.MySQLCursorDict and you'll have the same functionality:

try:
    cursor = self.connection.cursor(dictionary=True)
    cursor.execute("SELECT * FROM domains")
    domains = cursor.fetchall()
    return domains
except Error as error:
    print(error)

More details in https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

Nuno Mariz
  • 561
  • 3
  • 8