使用psycopg2从python中的元组中提取字符串

时间:2015-11-23 10:39:07

标签: python postgresql tuples psycopg2

我在python中编写了一个web.py服务来访问PostGres并获取特定数据库中的表名。

CODE:

 def GET(self,r):
          web.header('Access-Control-Allow-Origin',      '*')
          web.header('Access-Control-Allow-Credentials', 'true')
          tables = []
          datasetID = web.input().dataSetID
          cursor = conn.cursor()
          cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';")
          tablesWithDetails =    cursor.fetchall()
          print tablesWithDetails
          for x in tablesWithDetails:
            x.replace("(", "")
            x.replace(")","")
            tables.append(x)
            print tables;

这将打印表格如下,

[('acam_datasegregationdetails',), ('acam_datasegregationheader',), ('idn_accessinformation',), ('idn_b2cuseraccountmapping',), ('idn_b2cuserdevicemapping',), ('idn_b2cusers',), ('idn_roles',), ('idn_useraccountmapping')]

需要输出:

['acam_datasegregationdetails', 'acam_datasegregationheader', idn_accessinformation', 'idn_b2cuseraccountmapping', 'idn_b2cuserdevicemapping', 'idn_b2cusers', 'idn_roles', 'idn_useraccountmapping']

1 个答案:

答案 0 :(得分:4)

删除该循环而改为

tables = [t[0] for t in tablesWithDetails]

它将构建一个包含结果集中每个元组的第一个元素的列表。

甚至更简单(也更便宜),如果你想要一个列表然后返回一个数组,它将被Psycopg改编成一个列表:

cursor.execute("""
    select array_agg(relname)
    from pg_class
    where relkind='r' and relname !~ '^(pg_|sql_)';"
""")
tables = cursor.fetchall()[0][0]