Using MySQLdb to return values - Python
Question: I have a table called `coords` and it is defined as:

    
    
    mysql> describe coords;
    +-----------+--------------+------+-----+------------------+----------------+
    | Field     | Type         | Null | Key | Default          | Extra          |
    +-----------+--------------+------+-----+------------------+----------------+
    | id        | int(11)      | NO   | PRI | NULL             | auto_increment |
    | location  | varchar(150) | NO   | UNI | NULL             |                |
    | latitude  | float(20,14) | YES  |     | 0.00000000000000 |                |
    | longitude | float(20,14) | YES  |     | 0.00000000000000 |                |
    -----------------------------------------------------------------------------
    

I am using the `MySQLdb` import in my Python script. The purpose of this table
is to store (as you can guess, but for clarity) location coordinates (but only
when I do not have the coordinates already for a particular location).

I will be querying this table in my Python program to see if I already have
coordinates for a pre-requested location. I'm doing this to speed up the use
of the `geopy` package that interrogates Google's Geolocation Service.

How do I store the returned floats that correspond to a location? So far I
have the following:

    
    
    myVar = cur.execute("SELECT latitude, longitude FROM coords WHERE location ='" + jobLocation + "';")
    if myVar == 1:
        print(cur.fetchone())
    else:
        try:
            _place, (_lat, _lon) = geos.geocode(jobLocation, region='GB', exactly_one=False)
            print("%s: %.5f, %.5f" % _place, (_lat, _lon))
        except ValueError as err:
           print(err)
    

The code works (well, not really...) but I have no idea of how to get the
returned coordinates into separate float variables.

Can you help?


Answer: When you do `cur.fetchone()`, you need to store the result somewhere:

    
    
    row = cur.fetchone()
    print row[0], row[1]
    

Now `row[0]` will contain the latitude, and row[1] the longitude.

If you do this when connecting:

    
    
    cur = con.cursor(mdb.cursors.DictCursor)
    

you can then use a dictionary to refer to the columns by name:

    
    
    row = cur.fetchone()
    print row["latitude"], row["longitude"]
    

