我使用For循环为三个变量distance,cty,ctry赋值。然后我想将值存储在sqlite3的表中。不幸的是,程序只在sqlite3数据库中存储For循环的第一行值:
14004 GOROKA PAPUA NEW GUINEA
代码:
from math import sin, cos, sqrt, atan2, radians
import sqlite3
R = 6373.0
conn = sqlite3.connect('global_airports_sqlite.db')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Ports')
cur.execute('''
CREATE TABLE Ports ( Delta INTEGER, City TEXT, Country TEXT )''')
coords= 'SELECT lat_decimal, lon_decimal, city, country FROM airports ORDER
BY id ASC LIMIT 10'
for cord in cur.execute(coords):
lat2 = radians(cord[0])
lon2 = radians(cord[1])
cty = cord[2]
ctry = cord[3]
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = int(R * c)
cur.execute('INSERT INTO Ports (Delta, City, Country) VALUES (?,?,?)',
(distance, cty, ctry))
conn.commit()
如何将所有10个值存储在我的三列中:Delta,City,Country?
答案 0 :(得分:2)
我不确定sqlite3
包裹,我亲自使用pymysql
;但是,我认为流程应该是一样的;
因此,我认为在开始for循环之前,您可能需要先获取数据吗?
...
cur.execute('DROP TABLE IF EXISTS Ports')
cur.execute('''
CREATE TABLE Ports ( Delta INTEGER, City TEXT, Country TEXT )''')
coords= 'SELECT lat_decimal, lon_decimal, city, country FROM airports ORDER BY id ASC LIMIT 10')
cur.execute(coords)
data = cur.fetchall()
for records in data:
...
试一试
答案 1 :(得分:1)
您需要使用两个不同的游标,一个用于SELECT
查询,另一个用于INSERT
。当您执行第一个INSERT
查询时,游标不再保留SELECT
查询的剩余结果,因此循环结束。
from math import sin, cos, sqrt, atan2, radians
import sqlite3
R = 6373.0
conn = sqlite3.connect('global_airports_sqlite.db')
cur = conn.cursor()
cur2 = conn.cursor()
cur.execute('DROP TABLE IF EXISTS Ports')
cur.execute('''
CREATE TABLE Ports ( Delta INTEGER, City TEXT, Country TEXT )''')
coords= 'SELECT lat_decimal, lon_decimal, city, country FROM airports ORDER
BY id ASC LIMIT 10'
for cord in cur.execute(coords):
lat2 = radians(cord[0])
lon2 = radians(cord[1])
cty = cord[2]
ctry = cord[3]
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
distance = int(R * c)
cur2.execute('INSERT INTO Ports (Delta, City, Country) VALUES (?,?,?)',
(distance, cty, ctry))
conn.commit()