Python mysql connector returns tuple

落爺英雄遲暮 提交于 2020-03-16 05:24:51

问题


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()

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'),)

回答1:


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):

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;




回答2:


if you want to access just the data in the row you need to go into the dictionary

first you must make it true in the cursor

cur = db.cursor( buffered=True , dictionary=True)

then the result will be like this :

{'Decimal' : '991837'}

i'm sure the Decimal is your row name so when you need to access to the value do this

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['Decimal'])

cursor.close()

i hope it works for i was looking for this solution for the past 2 days and no answers the only way i debugged i opened the debugger and print out all the variables
have fun with Python :)



来源:https://stackoverflow.com/questions/35300200/python-mysql-connector-returns-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!