首页 > 解决方案 > 如何解决在 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

标签: pythonsqliteprintingtupleshex

解决方案


SELECT hex(name || age) AS name FROM Ages将为每一行检索一个列,并且您也尝试使用以下命令打印第二列:

print(str(row[0]), row[1])

只需执行以下操作:

print(str(row[0]))

推荐阅读