4

I ran into this issue while making a practice script to teach myself some Python and about the mysql.connector library. When I perform a query with a single column and print the values, I get results like:

('tech-pc-1',) #Python 3.4.3 (u'tech-pc-1',) #Python 2.7.6

However, when I perform a query with multiple columns and I print the values I get the results I want.

tech-pc-1 jdoe

I'm doing this on a server running Ubuntu 14.04.

from mysql.connector import (connection)
import datetime<br>
conn = connection.MySQLConnection(user='user',password='pass',host='host',database='db')

single_col_query = "select comp from logons where dt between %s and %s"
multi_col_query = "select comp,user from logons where dt between %s and %s"

end_dt = datetime.datetime.now()
begin_dt = datetime.datetime(end_dt.year, end_dt.month, 1, 0, 0, 0)

cursor = conn.cursor()

cursor.execute(single_col_query, (begin_dt, end_dt))
for(comp) in cursor:
    print(comp)  # ex. ('tech-pc-1',) or (u'tech-pc-1',)

cursor.execute(multi_col_query, (begin_dt, end_dt))
for(comp,user) in cursor:
    print(comp, user)  # ex. tech-pc-1 jdoe

cursor.close()
conn.close()

I have a couple of questions:

  1. Why does this happen?
  2. How do I fix this?
1
  • 1
    This looks very normal to me? I'm not sure what you're expecting to see. Commented Oct 27, 2015 at 18:15

1 Answer 1

6

You always get a tuple even if only one column is returned. In your second example, you unpack the tuple, but in the first one you don't, so you see the repr() of the tuple.

Either unpack it in the loop:

for comp, in cursor:

or just reference the element directly when you print:

print(comp[0])

Note there's no need for parentheses in the for statement, even when unpacking.

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

Comments

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.