在 SQL 语句中包含变量的问题 - 在 Python 3.4 中

Issue with including variable in SQL statement - in Python 3.4

我正在尝试计算坐标对之间的距离并用结果更新 table 列。

当我打印循环结果时,每对坐标之间的距离计算工作正常(见屏幕截图)。

但是添加到 table 的距离存在问题(参见屏幕截图)- 所有行的距离均为 15886,点之间的距离为 (-36.8090839, 174.718904) 和 (0, 0).

我的更新命令的构建方式似乎存在问题 - 特别是添加来自 table 的坐标(纬度和经度)变量。

有人可以指出我做错了什么吗?

我是 python 的新手。

import _sqlite3,  time,  datetime, gpxpy.geo
conn = _sqlite3.connect('SpatialDB')
c = conn.cursor()

lat1 = -36.8090839
lon1 = 174.718904

c.execute('Select * FROM Media')
data = c.fetchall()
for row in data:
    lat2 = row[1]
    lon2 = row[2]
    dist = gpxpy.geo.haversine_distance(lat1, lon1, lat2, lon2)/1000
    SQLCommand =("UPDATE Media SET LastQueried = Current_Timestamp, Distance  = ?");
    value =  [dist]
    c.execute(SQLCommand, value)
    print(dist)

conn.commit()
c.close()
conn.close()

distance 值对于 for 循环中的每一行都是不同的。因为 update 语句在 for 循环中,每次 distance 列(对于所有行)更新为当前行的值,因为没有 where 子句指定要 update 的行。因此,您会在 distance 列中看到相同的值(距离 for 循环的最后一个值)。

假设 business 对于每一行都是唯一的,将其用作 where 子句以便更新相应的行。

import _sqlite3,  time,  datetime, gpxpy.geo
conn = _sqlite3.connect('SpatialDB')
c = conn.cursor()

lat1 = -36.8090839
lon1 = 174.718904

c.execute('Select * FROM Media')
data = c.fetchall()
for row in data:
    lat2 = row[1]
    lon2 = row[2]
    busns= row[0]
    dist = gpxpy.geo.haversine_distance(lat1, lon1, lat2, lon2)/1000
    c.execute("UPDATE Media SET LastQueried = ?, Distance  = ? WHERE Business = ?",(Current_Timestamp,dist,busns))

conn.commit()
c.close()
conn.close()