2012-05-15 26 views

Respuesta

2

La pregunta es acerca del uso de psycopg2 de Python para hacer cosas con postgres. Aquí hay dos funciones prácticas:

def table_exists(con, table_str): 

    exists = False 
    try: 
     cur = con.cursor() 
     cur.execute("select exists(select relname from pg_class where relname='" + table_str + "')") 
     exists = cur.fetchone()[0] 
     print exists 
     cur.close() 
    except psycopg2.Error as e: 
     print e 
    return exists 

def get_table_col_names(con, table_str): 

    col_names = [] 
    try: 
     cur = con.cursor() 
     cur.execute("select * from " + table_str + " LIMIT 0") 
     for desc in cur.description: 
      col_names.append(desc[0])   
     cur.close() 
    except psycopg2.Error as e: 
     print e 

    return col_names 
+3

buena respuesta para la pregunta incorrecta. –

22

pg_class almacena toda la información requerida.

ejecutar la consulta siguiente devolverá tablas definidas por el usuario como una tupla en una lista

conn = psycopg2.connect(conn_string) 
cursor = conn.cursor() 
cursor.execute("select relname from pg_class where relkind='r' and relname !~ '^(pg_|sql_)';") 
print cursor.fetchall() 

de salida:

[('table1',), ('table2',), ('table3',)] 
+1

¿Cómo me meto en una matriz para el banquete? – ihue

20

Esto hizo el truco para mí:

cursor.execute("""SELECT table_name FROM information_schema.tables 
     WHERE table_schema = 'public'""") 
for table in cursor.fetchall(): 
    print(table) 
+1

Gracias kalu rigth al punto y universal. – peter