简体   繁体   English

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

[英]Extract string from a Tuple in python with psycopg2

I have written a web.py service in python to access PostGres and get the table names inside the specific database. 我已经在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;

This prints the table as follows, 这将打印表如下,

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

Needed Output: 所需的输出:

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

Drop that loop and in instead do 放下该循环并改为

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

It will build a list containing the first element of each tuple in the result set. 它将构建一个列表,其中包含结果集中每个元组的第一个元素。

Or even simpler (and cheaper), if you want a list then return an array which will be adapted to a list by Psycopg: 甚至更简单(也更便宜),如果您想要一个列表,则返回一个数组,该数组将被Psycopg调整为列表:

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

The problem is due this piece of code 问题是由于这段代码

tables.append(x)

When you execute cursor.fetchall() you will get a List of Tuples 当您执行cursor.fetchall()您将获得一个元组列表

and when you do for x in tablesWithDetails: you are iterating over the list by one tuple at a time 并且当您for x in tablesWithDetails:one tuple at a time遍历列表

So when you do tables.append(x) you are appending a single element tuple to the list 因此,当执行tables.append(x)时,您tables.append(x)单个元素元组追加到列表中

To change that you could do this tables.append(x[0]) it appends the first element of the tuple 要更改,您可以执行此表tables.append(x[0])会附加元组的第一个元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM