Python mysql连接器返回元组 [英] Python mysql connector returns tuple

查看:235
本文介绍了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):

此方法检索查询结果集的下一行并返回一个 序列,如果没有更多行可用,则为无".默认情况下, 返回的元组由MySQL服务器返回的数据组成, 转换为Python对象.如果游标是原始游标,则不会这样 发生转换;

This method retrieves the next row of a query result set and returns a single sequence, or None if no more rows are available. By default, the returned tuple consists of data returned by the MySQL server, converted to Python objects. If the cursor is a raw cursor, no such conversion occurs;

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆