drg
drg

Reputation: 198

Python MySql Select Single Column Returning Weird Values

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?

Upvotes: 4

Views: 2812

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599876

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.

Upvotes: 6

Related Questions