Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
迭代python mysql输出_Mysql_Python 3.x_Tuples_Mysql Python - Fatal编程技术网

迭代python mysql输出

迭代python mysql输出,mysql,python-3.x,tuples,mysql-python,Mysql,Python 3.x,Tuples,Mysql Python,代码是 import mysql.connector mydb=mysql.connector.connect(host="localhost",username="root",password="something",database="mrbean") mycursor=mydb.cursor() mycursor.execute("select * from store") myresu

代码是

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

(2010年,“笔记本”,25页,无)
回溯(最近一次呼叫最后一次):
文件“C:/Users/sajim/Documents/python random programs/python mysql.py”,第10行,在
印刷品(一)[1]
TypeError:“非类型”对象不可下标
您编写的代码:

print(i)[1]
它首先打印
myresult
iterable的第i个值,然后尝试从调用
print
的返回值中提取元素1。但是
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
顺序返回的(理论上,关系(即表)没有顺序,但实际上数据库引擎将以确定的顺序返回行,这通常是主键顺序)。然后:


也许您应该使用
打印(myresult[1])
?因为您想要结果的第一行?不,它给出了每行中的所有第二列数据,那么您可以将其更改为
print(myresult[0])
,并省略“for i in myresult:”这正确地给出了输出,但如果我想使用for循环进行迭代并只打印某一行。这是不可能的?比如说,如果我只想打印前5行或最后5行,那么像你说的那样手工书写每一行都会耗费时间谢谢你这么好的回答:)
mycursor.execute("select * from store order by id desc limit 5")
myresult = mycursor.fetchall()
for row in myresult:
    print(row)