Python and MySQLdb

I have the following query that I execute using a Python script (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 determined when the script is executed. My concern is that the code snippet above does not return results; which means that the way the request is executed is unstable. I executed an SQL query (including given variables with actual values ​​and returned the correct number of results).

If I modify the query simply as a simple SELECT FROM ( SELECT * FROM poi_table) query , it returns the results. What's going on here?

EDIT: Calculation of Encapsulated Haversin Formula in Parentheses

+3
source share
2 answers

AFAIK execute().
MySQLdb .

, execute() .
, execute() .
fetchone() fetchmany() 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
+3

, HAVING WHERE distance < @radius ?

+2

Source: https://habr.com/ru/post/1748269/


All Articles