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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.