可以´t将查询结果赋给python变量

htrmnn0y  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(348)

我有个问题:

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',)],所以我不能在其他方法中使用它,因为我得到以下错误:

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

如果使用这样的变量:

LATCH_APP_ID = "ybDWvzU4iijnqqX8xAxx"

脚本运行正常
有人能帮我吗?

qlvxas9a

qlvxas9a1#

看来 cursor.fetchall() 已返回:

[(u'ybDWvzU4iijnqqX8xAxx',)]

所以您只需要从结构中的with中提取字符串:

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

相关问题