本文介绍了Python mysql连接器返回元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过mysql连接器连接到mysql数据库,并运行一个简单的查询以提取ID列表.我需要遍历该列表,并将它们传递给其他代码.由于某种原因,我得到了一个元组列表.这是预期的行为吗?如果没有,我在做什么错?这是我的代码段:

I am connecting to mysql database via mysql connector and running a simple query to pull a list of IDs. I need to loop over that list and pass them into some other code. For some reason I am getting a list of tuples. Is this expected behavior? If not, what am I doing wrong?Here is the snippet of my code:

import mysql.connector
conn = mysql.connector.connect(host='127.0.0.1', database='t', user='r', password='pwd')
cursor = conn.cursor()
query = ( "select id from T where updated < '%s'" % (run_date) )
cursor.execute(query)
for row in cursor:
   print (row)

cursor.close()

我从d/b中的INT字段得到以下信息:

I am getting the following back (from an INT field in d/b):

(Decimal('991837'),)
(Decimal('991838'),)
(Decimal('991839'),)
(Decimal('991871'),)
(Decimal('991879'),)
(Decimal('991899'),)
(Decimal('992051'),)
(Decimal('992299'),)
(Decimal('992309'),)

推荐答案

是的,这是预期的行为.使用游标作为可迭代对象基本上等效于使用fetchone()方法对其进行循环.从 fetchone()的文档中(强调我的意思):

Yes, this is expected behavior. Using the cursor as an iterable is basically equivalent to looping over it using the fetchone() method. From the documentation for fetchone() (emphasis mine):

这篇关于Python mysql连接器返回元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:33
查看更多