2017-10-10 129 views
0

最終我想輸出主機到列表。從mysql DB查詢結果到列表

try: 
    cnx = mysql.connector.connect(user='root', password='passwd', 
database='some_db') 
    cursor = cnx.cursor() 
except mysql.connector.Error as err: 
    print("Something went wrong: {}".format(err)) 

retrieveQuery = ("SELECT host_name,product from server") 
cursor.execute(retrieveQuery) 
for host,prod in cursor: 
print ("{},{}".format(host,prod)) 

結果看起來不錯:主機1,的PowerEdge]

retrieveQuery = ("SELECT host_name from server") 
cursor.execute(retrieveQuery) 
for host in cursor: 
print ("{}".format(host)) 

結果:(u'host1' ,)

爲什麼我看到(U」)使用相同的代碼,但何時只選擇一列? 任何幫助深表感謝

+0

你想知道爲什麼會出現字符串或者爲什麼之前'u'有逗號(或兩者)? – Unni

回答

0

cursor行結果總是tuple類型,請嘗試:

for row in cursor: 
    print ("{}".format(row.host_name)) 

for host, in cursor: 
    print ("{}".format(host))