2

I'm using the MySQL connector provided by MySQL in a Python script. I can successfully query data, however, building a return is causing some problems for me.

Here's a basic database table

CREATE TABLE users(
uuid char(64) not null primary key,
firstname varchar(32) not null,
lastname varchar(32) not null,
email varchar(64) not null,
user_name varchar(32) not null,
password varchar(64) not null
);

INSERT INTO users VALUES
('7503637e-b8a7-44c2-822b-69ccb8ebfae0', 'Andy' , 'Apple'  , '[email protected]'  , 'aaple'  , 'abc123')

Here's a simple Python script

import mysql.connector

config = {
    'host' : '127.0.0.1',
    'user': 'root',
    'password' : 'password',
    'database' : 'database'
}

fields = ('uuid', 'firstname', 'lastname')
query = 'SELECT ' + ', '.join(fields) + ' FROM users'

cnx = mysql.connector.connect(**mysqlConfig)
cursor = cnx.cursor()
cursor.execute(query)

results = {}
for (uuid, firstname, lastname) in cursor:
    results[uuid] = {
        'first_name': firstname,
        'last_name' : lastname
    }

cursor.close()
cnx.close()

While this works, I'm trying to figure out a way to dynamically build the result variable. I don't want to have to add a new field name both to the fields variable as well as the tuple in the for loop.

I've been trying figure out a way to accomplish this using this code

columnNames = cursor.column_names
# columnNames = (u'uuid', u'fname', u'lname')

However, cursor.column_names returns a tuple of strings.

How can build a result dictionary containing the values found in the "fields" variable without having to add the new column name in 2 separate places?

1 Answer 1

2

So, after many hours, I finally found the answer through straight trial and error. Hopefully this will help someone

import mysql.connector

config = {
    'host' : '127.0.0.1',
    'user': 'root',
    'password' : 'password',
    'database' : 'database'
}

fields = ('uuid', 'firstname', 'lastname')
query = 'SELECT ' + ', '.join(fields) + ' FROM users'

cnx = mysql.connector.connect(**mysqlConfig)
cursor = cnx.cursor()
cursor.execute(query)

results = []

row = self.cursor.fetchone()
while row is not None:
    recordData = dict(zip(self.cursor.column_names, row))
    results.append(recordData)
    row = self.cursor.fetchone()


cursor.close()
cnx.close()

This will return a list of dictionaries containing the data. If you want to accomplish this via SQLite, use the following code in the while loop

resultSet = []
rowPosition = 0

row = self.cursor.fetchone()

while row is not None:
    rowDictionary = {}

    for columnName in row.keys():
        rowDictionary[columnName] = row[rowPosition]
        rowPosition += 1

    rowPosition = 0
    resultSet.append(rowDictionary)
    row = self.cursor.fetchone()
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.