python - 如何解决在 python 3 中创建 SQL Lite 数据库并为第一行名称和年龄打印十六进制的 Traceback 错误?
问题描述
尝试在 Python 中创建 SQL 数据库并插入一些基本数据,然后返回数据库中姓名/年龄第一行的十六进制值,然后在 python 中打印,但不断收到元组错误。
谢谢
import sqlite3
conn = sqlite3.connect('Exercise_Ages.sqlite')
cur = conn.cursor()
cur.execute('''DROP TABLE IF EXISTS Ages''')
cur.executescript('''CREATE TABLE Ages (name VARCHAR(128), age INTEGER);
DELETE FROM Ages;
INSERT INTO Ages (name, age) VALUES ('Trudie', 18);
INSERT INTO Ages (name, age) VALUES ('Marley', 26);
INSERT INTO Ages (name, age) VALUES ('Elshan', 17);
INSERT INTO Ages (name, age) VALUES ('Reese', 32);
INSERT INTO Ages (name, age) VALUES ('Lex', 31);
INSERT INTO Ages (name, age) VALUES ('Briagha', 16);''')
conn.commit()
sqlstr = 'SELECT hex(name || age) AS name FROM Ages ORDER BY age DESC LIMIT 10'
for row in cur.execute(sqlstr):
print(str(row[0]), row[1])
cur.close()
Traceback (most recent call last):
File "<ipython-input-63-ddbebe584cc3>", line 22, in <module>
print(str(row[0]), row[1])
IndexError: tuple index out of range
解决方案
这SELECT hex(name || age) AS name FROM Ages
将为每一行检索一个列,并且您也尝试使用以下命令打印第二列:
print(str(row[0]), row[1])
只需执行以下操作:
print(str(row[0]))
推荐阅读
- python - Python parse xml and build dataframe
- wordpress - WP 查询仅从两个孩子返回有限的项目
- javascript - MongoDB中根据ID更新多个文档
- angular - 导入 cytoscape.js 作为 ESM 模块
- c# - 我想在前 9 个字符之后找到一个名字
- sqlite - 如何连接日期后的三个表?
- sql - SQL WHERE IN() 性能优化
- python - Python正则表达式匹配精确数字
- r - 有没有办法避免使用闪亮的重新计算绘制绘图之间的闪烁
- list - F# - 使用 List.foldBack 将列表连接到自身