有人可以解释一下如何在当前数据库中获取表格吗?
我正在使用postgresql-8.4 psycopg2。
答案 0 :(得分:46)
这对我有用:
cursor.execute("""SELECT table_name FROM information_schema.tables
WHERE table_schema = 'public'""")
for table in cursor.fetchall():
print(table)
答案 1 :(得分:27)
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',)]
答案 2 :(得分:4)
问题是关于使用python的psycopg2来做postgres的事情。这里有两个方便的功能:
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 :(得分:1)
如果您使用psql,则可以输入:
\d
http://www.postgresql.org/docs/9.1/static/app-psql.html
如果您正在运行SQL,则可以键入:
SELECT * FROM tables;
http://www.postgresql.org/docs/current/interactive/information-schema.html
如果您需要有关其用法的统计信息,可以输入:
SELECT * FROM pg_stat_user_tables;
http://www.postgresql.org/docs/current/interactive/monitoring-stats.html
答案 4 :(得分:0)
这是一个包含 Python3
参数并生成 connect()
Python
用于输出的 list()
片段:
conn = psycopg2.connect(host='localhost', dbname='mySchema',
user='myUserName', password='myPassword')
cursor = conn.cursor()
cursor.execute("""SELECT relname FROM pg_class WHERE relkind='r'
AND relname !~ '^(pg_|sql_)';""") # "rel" is short for relation.
tables = [i[0] for i in cursor.fetchall()] # A list() of tables.
答案 5 :(得分:-3)
您可以将此代码用于python 3
window.open()