Python Forum

Full Version: Creating Dynamic Variable Names
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I was looking around at the MySQLdb extension and noticed that returns are a field number instead of a field name.
I was working on building a function to convert, but I got stuck.
Everything works except the line where I have result= data[x] even when I have it not commented.

Stupid editor killed the post and it won't let me edit.
Edit admin:
Yes can keep formatting when copy,mark all and use "Remove Formatting" button.
import re
import MySQLdb

def fieldconverter( result ):
        statement = re.sub(r'\A(SELECT\s){1}|FROM(.*?)\Z', "", result)
        # Now we have  a list of fields.  Loop through them
        splitstatement = statement.split(", ")
        x = 0
        for a in splitstatement:
            print "Field Number: %s"  % x + " Field Name: %s" % a
            #result[a] = data[x]
            x += 1

        return result

print "Latias flies around at high speed."
# Connect to the database
db = MySQLdb.connect("siteground255.com", "superla9_latios", "R{-q*MNJILE+", "superla9_forums")

cursor = db.cursor()
sql = "SELECT uid, username, email FROM tpc_users WHERE username='Arceus'"
cursor.execute(sql)
data = cursor.fetchone()
result = fieldconverter(sql)
print "Username: %s " % data[1] + " Uid: %i" % data[0]
db.close()
So result is a dictionary, which means you have to initialize it with an empty dictionary (result={} before the loop...)
(Oct-21-2016, 09:24 PM)Ofnuts Wrote: [ -> ]So result is a dictionary, which means you have to initialize it with an empty dictionary (result={} before the loop...)

Thanks so much.  The code works perfectly now.  This makes it much easier to handle queries since knowing the position of a field can be tedious.  Now I just need to find a way to resolve queries that use all fields.
I was able to get it to work for selecting all fields.

Final Code: https://github.com/dragonexpert/Python-M...convert.py