Czy ktoś może wyjaśnić, w jaki sposób mogę uzyskać tabele w bieżącej bazie danych?Jak uzyskać tabele w postgres przy użyciu psycopg2?
Używam postgresql-8.4 psycopg2.
Czy ktoś może wyjaśnić, w jaki sposób mogę uzyskać tabele w bieżącej bazie danych?Jak uzyskać tabele w postgres przy użyciu psycopg2?
Używam postgresql-8.4 psycopg2.
Jeśli używasz psql, można wpisać:
\d
http://www.postgresql.org/docs/9.1/static/app-psql.html
Jeśli używasz SQL, można wpisać:
SELECT * FROM tables;
http://www.postgresql.org/docs/current/interactive/information-schema.html
Jeśli chcesz statystyki dotyczące ich użycia, możesz wpisać:
SELECT * FROM pg_stat_user_tables;
http://www.postgresql.org/docs/current/interactive/monitoring-stats.html
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
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',)]
Jak uzyskać formułę macierzy? – ihue
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)
Dziękuję kalu rigth do rzeczy i uniwersalne. – peter
dobra odpowiedź za złe pytanie. –