gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:29:53 30 4
gpt4 key购买 nike

我已经用 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;

打印表格如下,

[('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']

最佳答案

放弃那个循环,改为执行

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]

关于python - 使用 psycopg2 从 python 中的元组中提取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33868982/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com