9

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

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

4

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 Comments

Not really related to the original question I asked, but how to I convert (Decimal('992309'),) to 992309 ?
@epipko Grab the first element of the tuple ([0]), then you've got a Decimal object which you can convert to int if you need to.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.