迭代python mysql输出

问题描述

代码

import MysqL.connector
mydb=MysqL.connector.connect(host="localhost",username="root",password="something",database="mrbean")

mycursor=mydb.cursor()
mycursor.execute("select * from store")

myresult=mycursor.fetchall()

for i in myresult:
    print(i)

这给出了正确的输出,但如果我只想要一行 我确实喜欢这个 print(i)[1] 这给了我一个错误为什么?

错误-

(2010,'Note Book',25,None)
Traceback (most recent call last):
  File "C:/Users/sajim/Documents/python random programes/python MysqL.py",line 10,in <module>
    print(i)[1]
TypeError: 'nonetype' object is not subscriptable

解决方法

您编码:

print(i)[1]

首先打印 myresult 可迭代对象的 ith 值,然后尝试提取元素编号。 1 来自调用 print 的返回值。但是 print 函数返回 None,这就是为什么您会得到异常。

如果你想要一行:

myresult = mycursor.fetchone()
print(myresult)

如果您已检索到所有行:

myresult = mycursor.fetchall()
print(myresult[0]) # first row

如果要打印前五行:

myresult = mycursor.fetchall()
for row in myresult[0:5]:
    print(row)

但使用以下方法仅检索 5 行会更有意义:

mycursor.execute("select * from store limit 5")
myresult = mycursor.fetchall()
for row in myresult:
    print(row)

如果要打印最后 5 行:

myresult = mycursor.fetchall()
for row in myresult[-5:]:
    print(row)

但不是读取所有行,而是假设列 id 是主键并且行以 id 顺序返回(理论上没有关系的顺序,即表,但实际上数据库引擎将按确定的顺序返回行,这通常是按主键顺序)。然后:

mycursor.execute("select * from store order by id desc limit 5")
myresult = mycursor.fetchall()
for row in myresult:
    print(row)