我从数据库中的表中选择一列。我想遍历每个结果。为什么当我这样做时,它是一个元组而不是一个值?

con = psycopg2.connect(…)
cur = con.cursor()
stmt = "SELECT DISTINCT inventory_pkg FROM {}.{} WHERE inventory_pkg IS NOT NULL;".format(schema, tableName)
cur.execute(stmt)
con.commit()
referenced = cur.fetchall()
for destTbl in referenced:#why is destTbl a single element tuple?
    print('destTbl: '+str(referenced))
    stmt = "SELECT attr_name, attr_rule FROM {}.{} WHERE ppm_table_name = {};".format(schema, tableName, destTbl)#this fails because the where clause gets messed up because ‘destTbl’ has a comma after it
    cur.execute(stmt)

最佳答案

因为db api就是这样做的:总是为结果中的每一行返回一个元组。
在需要的地方引用destTbl[0]非常简单。

09-26 07:02