2012-05-15 11 views

Odpowiedz

2

Pytanie jest o używaniu psycopg2 Pythona robić rzeczy z PostgreSQL. Oto dwie przydatne funkcje:

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

dobra odpowiedź za złe pytanie. –

22

pg_class przechowuje wszystkie wymagane informacje.

wykonując poniższe zapytanie zwróci zdefiniowane przez użytkownika tabele krotki w liście

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() 

wyjściowa:

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

Jak uzyskać formułę macierzy? – ihue

20

zrobił to trick dla mnie:

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

Dziękuję kalu rigth do rzeczy i uniwersalne. – peter

Powiązane problemy