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

2024-09-27 00:20:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了一篇网页.pypython中的服务来访问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;

这将打印如下表:

^{pr2}$

所需输出:

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

Tags: web网页tablesaccesscursorreplacecontrolheader
2条回答

扔掉那个循环,然后进去

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

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

或者更简单(也更便宜),如果您想要一个列表,那么返回一个数组,它将由Psycopg调整为一个列表:

^{pr2}$

问题出在这段代码上

tables.append(x)

当您执行cursor.fetchall()时,您将得到一个元组列表

当您执行for x in tablesWithDetails:操作时,您正在按one tuple at a time对列表进行迭代

所以当你做tables.append(x)时,你就是在列表中附加一个元素元组

为了改变您可以这样做tables.append(x[0]),它附加了元组的第一个元素

相关问题 更多 >

    热门问题