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

标签 python python-3.x sqlite

我正在使用 For 循环为三个变量 distance、cty、ctry 赋予值。然后我想将这些值存储在 sqlite3 的表中。不幸的是,该程序仅将 For 循环的第一行值存储在 sqlite3 数据库中:

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?

最佳答案

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

尝试一下

关于python - 使用python3中的For循环在sqlite3中创建3列x 10行表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48431679/

相关文章:

sql - 在SQlite中使用大于运算符时,将返回空白值

android - 如何为其项目填充具有两种不同布局的 CustomListView?

python - 获取替换数据(python 3.3)

python - 在 Google App Engine 中使用 mapreduce 的简单反例

python - 安装 Anaconda3 会将 Mac OS X 默认 Python 版本更改为 3.4 吗?

python - virtualenv 使用升级后的系统默认 pip

python - 以最聪明的 pythonic 方式将用户返回到 flask 中的引荐来源网址

python - 在文本框中搜索单词并将光标移动到文本框中的下一个匹配项?

Python 无法写入引用 'FileNotFoundError' 的文件

android - 如何从 Sqlite 数据库中检索 DATETIME 格式