Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and MySQLdb

Tags:

python

mysql

I have the following query that I'm executing using a Python script (by using the MySQLdb module).

conn=MySQLdb.connect (host = "localhost", user = "root",passwd = "<password>",db = "test")
cursor = conn.cursor ()
preamble='set @radius=%s; set @o_lat=%s; set @o_lon=%s; '%(radius,latitude,longitude)
query='SELECT *, (6371*1000 * acos(cos(radians(@o_lat)) * cos(radians(lat)) * cos(radians(lon) - radians(@o_lon)) + sin(radians(@o_lat)) * sin(radians(lat))) as distance FROM poi_table HAVING distance < @radius ORDER BY distance ASC LIMIT 0, 50)'
complete_query=preamble+query
results=cursor.execute (complete_query)
print results

The values of radius, latitude, and longitude are not important, but they are being defined when the script executes. What bothers me is that the snippet of code above returns no results; essentially meaning that the way that the query is being executed is wonky. I executed the SQL query (including the set variables with actual values, and it returned the correct number of results).

If I modify the query to just be a simple SELECT FROM query (SELECT * FROM poi_table) it returns results. What is going on here?

EDIT: Encapsulated Haversine formula calculation within parenthesis

like image 715
GobiasKoffi Avatar asked Jul 22 '26 00:07

GobiasKoffi


2 Answers

AFAIK you can't run multiple statements using execute().
You can, however, let MySQLdb handle the value substitutions.

Note that there are two arguments being passed to execute().
Also, just running execute() doesn't actually return any results.
You need to use fetchone() or fetchmany() or fetchall().

cursor.execute('''
    SELECT *, 
        6371*1000 * acos(cos(radians(%s)) * 
        cos(radians(lat)) * cos(radians(lon) - radians(%s)) + 
        sin(radians(%s)) * sin(radians(lat))) as distance 
    FROM 
        poi_table 
    WHERE distance < %s
    ORDER BY distance ASC 
    LIMIT 0, 50''', (latitude, longitude, latitude, radius,))
results = cursor.fetchall()
print results
like image 92
mechanical_meat Avatar answered Jul 23 '26 14:07

mechanical_meat


Are you sure that the HAVING clause shouldn't be WHERE distance < @radius instead?

like image 36
Ben Hoffstein Avatar answered Jul 23 '26 14:07

Ben Hoffstein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!