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

Saj*_*ran 1 python postgresql tuples psycopg2

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

码:

 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;
Run Code Online (Sandbox Code Playgroud)

这将打印表如下,

[('acam_datasegregationdetails',), ('acam_datasegregationheader',), ('idn_accessinformation',), ('idn_b2cuseraccountmapping',), ('idn_b2cuserdevicemapping',), ('idn_b2cusers',), ('idn_roles',), ('idn_useraccountmapping')]
Run Code Online (Sandbox Code Playgroud)

所需的输出:

['acam_datasegregationdetails', 'acam_datasegregationheader', idn_accessinformation', 'idn_b2cuseraccountmapping', 'idn_b2cuserdevicemapping', 'idn_b2cusers', 'idn_roles', 'idn_useraccountmapping']
Run Code Online (Sandbox Code Playgroud)

Clo*_*eto 5

放下该循环并改为

tables = [t[0] for t in tablesWithDetails]
Run Code Online (Sandbox Code Playgroud)

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

甚至更简单(也更便宜),如果您想要一个列表,则返回一个数组,该数组将被Psycopg调整为列表:

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