我有一个title
, release
和synopsis
等领域的视频表。我想循环遍历每行并按特定顺序打印列:
con = sqlite3.connect("videos.db")
cur = con.cursor()
videos = "SELECT * FROM videos"
for videos in cur.execute('SELECT * FROM videos;'):
print("title:",videos[2])
print("release:",videos[3])
print("description:",videos[4])
print("-" * 10)
但这是不正确的,因为
- 我需要看到打印的是哪些列,而不是记住索引号,因为它们在我更新表时可能会发生变化,并且
- 我不认为元组是正确的输出。
预期结果:
title: video 1
release: 2022-01-01
description: video 1 description
---------
title: video 2
release: 2022-01-02
description: video 2 description
---------
最终目标是将每个导出为单独的XML文件。
据我所知,数组返回的第一个元素,因此在您的情况下videos
,包含由您的SQL请求返回的列列表。
你可以这样做:
videos = cur.execute('SELECT * FROM videos;')
# Get the index of the columns
title_index = videos[0].index("title");
release_index = videos[0].index("release");
description_index = videos[0].index("description_index");
for video in videos:
# And use those indexes to get the data
print("title:",videos[title_index])
print("release:",videos[release_index])
print("description:",videos[description_index])
print("-" * 10)