Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

In psycopg2, if I have a table:

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

If I do cursor.execute("SELECT * FROM mySchema.this_table LIMIT 1") then I check if color exists with: colnames = [desc[0] for desc in cursor.description] then search colnames for 'color'

then I think I get the row with: myrow = importCursor.fetchone()

but how do I get the 'color' value of that row? I tried color = importCursor.fetchone()['color'] but that doesn't work.

How do I get the color value of the row returned by that SELECT statement? I don't know how many columns there are in the table, or if the 'color' column will always be column #3 I have to do this for a bunch of columns in this table (check if exists, if does, return column value of row) so an efficient way is best!

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Select only some columns

If you select only certain columns, then you do know the column order.

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

Now you know that column 0 is name, 1 is age, 2 is color. So you can choose which one with something like myrow[1].

Get a map of columns first

You can get a map of the returned columns, and then use that to figure out where to fetch.

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

This should be relatively efficient, because you only need to calculate the column name list one time after the query, and then you can map the column name to a column number with simple list operations like index and in, which are much faster than hitting the database again.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda