4

我在制作一个练习脚本来教自己一些 Python 和 mysql.connector 库时遇到了这个问题。当我使用单列执行查询并打印值时,我得到的结果如下:

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

但是,当我执行多列查询并打印值时,我得到了我想要的结果。

tech-pc-1 jdoe

我在运行 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()

我有一些问题:

  1. 为什么会这样?
  2. 我该如何解决?
4

1 回答 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.

于 2015-10-27T18:32:54.243 回答