迭代 python mysql 输出
iterating over python mysql output
密码是
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
的 return 值。但是 print
函数 return 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
顺序 returned(理论上没有order 到一个关系,即 table,但实际上数据库引擎将 return 行按确定的顺序排列,这通常是主键顺序)。那么:
mycursor.execute("select * from store order by id desc limit 5")
myresult = mycursor.fetchall()
for row in myresult:
print(row)
密码是
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
的 return 值。但是 print
函数 return 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
顺序 returned(理论上没有order 到一个关系,即 table,但实际上数据库引擎将 return 行按确定的顺序排列,这通常是主键顺序)。那么:
mycursor.execute("select * from store order by id desc limit 5")
myresult = mycursor.fetchall()
for row in myresult:
print(row)