首页 文章

在python3中使用For循环在sqlite3中创建一个3列x 10行的表

提问于
浏览
1

我正在使用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?

2 回答

  • 2

    您需要使用两个不同的游标,一个用于 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()
    
  • 1

    我不确定 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:
      ...
    

    试试看

相关问题