Code Snippet: mysql_fetch_assoc in Python

Unfortunately the mySQL connector library for Python has no function like mysql_fetch_assoc known from PHP where you can fetch data from the database into an associative array. I needed that function for one of my actual projects, so I decided to write it on my own and share it, so that it maybe helps someone else with the same problem.

Here’s the code:

import mysql.connector
# Fetch data into assotiative array  
def mysql_fetch_assoc(link, query):
	out = []  
		cursor =
		rows = cursor.fetchall()     
		for row in rows:        
			data ={}
			for i in range(len(row)):          
				if row[i] != None:                        
					tmp = cursor.description            
					data[tmp[i][0]] = row[i]
	except Exception as err:
                # Your exception handling...
		print("Error in fetchassoc:")
		return out
### START ### 
default_config = {
  'user': 'YOUR_USERNAME',
  'password': 'YOUR_PASSWORD',
  'host': 'YOUR_DB_HOST',
  'database': 'YOUR_DB_NAME',
link = mysql.connector.connect(**default_config) # Establish connection
data = mysql_fetch_assoc("SELECT * FROM table") # Fetch the data

I think the code should be self-explanatory. Implement that in your project or modify it to your needs. 😉

Similar Posts: