获取一些值到变量中
Fetching some values into variables
我得到了这个代码:
cursor.execute('SELECT nom FROM productes WHERE listacompra = 1')
rows = cursor.fetchall()
for row in rows:
print(row[0])
我想将它 returns 放入一些变量中。我该怎么做?
编辑:
我想我没有正确解释自己。我想要的是让两个变量具有同一列的两个值,而不是同一行。例如:
有两行:
id 1, nam Natillas, listacompra 1
id 2, nom Chocolate, listacompra 1
我想要两个(或更多)变量,以便一个变量带有 "Natillas",另一个变量带有 "Chocolate"。
谢谢
rows = cursor.fetchall()
for row in rows:
print(row['<key of table field>'])
cursor.execute('SELECT nom FROM productes WHERE listacompra = 1')
rows = cursor.fetchall()
var1 = row[0][0] # or row['nom'] if you are fetching as dict
var2 = row[1][0]
显然,要使其正常工作,您必须确保查询 return 至少有两行。
旧答案
迭代器将return 一个表示查询中指定行的元组。例如,对于查询 SELECT id, password FROM users
,变量 row
将在第一个位置包含 id
值,在第二个位置包含 password
。
例如:
for row in rows:
id = row[0]
pwd = row[1]
或者,更准确地说:
for row in rows:
id, pwd = row
除非你在定义连接时指定选项cursorclass=pymysql.cursors.DictCursor
,在这种情况下它将return一个字典:
for row in rows:
id = row['id']
pwd = row['password']
我得到了这个代码:
cursor.execute('SELECT nom FROM productes WHERE listacompra = 1')
rows = cursor.fetchall()
for row in rows:
print(row[0])
我想将它 returns 放入一些变量中。我该怎么做?
编辑:
我想我没有正确解释自己。我想要的是让两个变量具有同一列的两个值,而不是同一行。例如:
有两行:
id 1, nam Natillas, listacompra 1
id 2, nom Chocolate, listacompra 1
我想要两个(或更多)变量,以便一个变量带有 "Natillas",另一个变量带有 "Chocolate"。
谢谢
rows = cursor.fetchall()
for row in rows:
print(row['<key of table field>'])
cursor.execute('SELECT nom FROM productes WHERE listacompra = 1')
rows = cursor.fetchall()
var1 = row[0][0] # or row['nom'] if you are fetching as dict
var2 = row[1][0]
显然,要使其正常工作,您必须确保查询 return 至少有两行。
旧答案
迭代器将return 一个表示查询中指定行的元组。例如,对于查询 SELECT id, password FROM users
,变量 row
将在第一个位置包含 id
值,在第二个位置包含 password
。
例如:
for row in rows:
id = row[0]
pwd = row[1]
或者,更准确地说:
for row in rows:
id, pwd = row
除非你在定义连接时指定选项cursorclass=pymysql.cursors.DictCursor
,在这种情况下它将return一个字典:
for row in rows:
id = row['id']
pwd = row['password']