如何检查列是否存在,如果存在,return 来自它的值

How to check if a column exists, if it does, return a value from it

在 psycopg2 中,如果我有 table:

+------+-----+-------+  
| name | age | color |  
+------+-----+-------+  
| Bob  |  25 | red   |  
| Bill |  50 | blue  |  
| Jane |  45 | black |  
+------+-----+-------+

如果我这样做 cursor.execute("SELECT * FROM mySchema.this_table LIMIT 1") 然后我检查颜色是否存在: colnames = [desc[0] for desc in cursor.description] 然后在 colnames 中搜索 'color'

然后我想我得到了: myrow = importCursor.fetchone()

但是如何获取该行的 'color' 值? 我试过了 color = importCursor.fetchone()['color'] 但这不起作用。

如何获取由 SELECT 语句编辑的 return 行的颜色值?我不知道 table 中有多少列,或者如果 'color' 列始终是第 3 列,我必须对 table 中的一堆列执行此操作(检查是否存在,如果存在,行的 return 列值)所以最好是有效的方法!

Select只有一些列

如果您 select 只有某些列,那么您确实知道列顺序。

cursor.execute("SELECT name, age, color FROM mySchema.this_table LIMIT 1")

现在您知道第 0 列是 name,第 1 列是 age,第 2 列是 color。因此,您可以选择 myrow[1].

之类的内容

先获取柱状图

您可以获得返回列的映射,然后使用它来确定从哪里获取。

column_names = [desc[0] for desc in cursor.description]
if 'color' in column_names:
    color = cursor.fetchOne()[column_names.index('color')]

这样应该是比较高效的,因为查询后只需要计算一次列名列表,然后就可以通过简单的列表操作如indexin,这比再次访问数据库要快得多。