无法将查询结果分配给python变量

时间:2018-06-11 19:50:37

标签: python mysql query-string mysql-python mysql-connector-python

我有这个问题:

import mysql.connector
cnx = mysql.connector.connect(user='root', password='xxx',
                              host='127.0.0.1',
                              database='xxxx')
cursor = cnx.cursor()
query = ("SELECT app_id FROM op_ids")
cursor.execute(query)
LATCH_APP_ID=cursor.fetchall()


cursor.close()
cnx.close()

数据库上app_id的值是 ybDWvzU4iijnqqX8xAxx 但是当我运行python脚本时,它会返回 [(u'ybDWvzU4iijnqqX8xAxx',)] ,所以我可以' t在其他方法中使用它因为我收到以下错误:

TypeError: cannot concatenate 'str' and 'list' objects

如果使用这样的变量:

LATCH_APP_ID = "ybDWvzU4iijnqqX8xAxx"

脚本运行正常

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

似乎cursor.fetchall()已经返回:

[(u'ybDWvzU4iijnqqX8xAxx',)]

所以你只需要从结构中提取字符串:

result = cursor.fetchall()

t = result[0]        # fetch the tuple from the first item in the list

LATCH_APP_ID = t[0]  # fetch the string from the first (only) item in the tuple