誰かが現在のデータベースでテーブルを取得する方法を説明できますか?
postgresql-8.4 psycopg2 を使用しています。
誰かが現在のデータベースでテーブルを取得する方法を説明できますか?
postgresql-8.4 psycopg2 を使用しています。
これは私にとってはうまくいきました:
cursor.execute("""SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'""")
for table in cursor.fetchall():
print(table)
pg_class には必要な情報がすべて格納されています。
以下のクエリを実行すると、ユーザー定義のテーブルがリスト内のタプルとして返されます
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()
出力:
[('table1',), ('table2',), ('table3',)]
質問は、python の psycopg2 を使用して postgres で処理を行うことに関するものです。2 つの便利な関数を次に示します。
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
このコードは python 3 で使用できます
import psycopg2
conn=psycopg2.connect(database="your_database",user="postgres", password="",
host="127.0.0.1", port="5432")
cur = conn.cursor()
cur.execute("select * from your_table")
rows = cur.fetchall()
conn.close()