我有一个postgreSQl数据库。我创建了很少的数据库用户,并为每个用户分配了某些角色。在我的python程序中,我需要获取数据库的用户及其相应的角色。如何获得这些信息?
答案 0 :(得分:1)
您可以对system catalogs执行查询。尝试查看pg_user
和pg_roles
表。他们的架构是:
test=# \d pg_user
View "pg_catalog.pg_user"
Column | Type | Modifiers
--------------+---------+-----------
usename | name |
usesysid | oid |
usecreatedb | boolean |
usesuper | boolean |
userepl | boolean |
usebypassrls | boolean |
passwd | text |
valuntil | abstime |
useconfig | text[] |
test=# \d pg_roles
View "pg_catalog.pg_roles"
Column | Type | Modifiers
----------------+--------------------------+-----------
rolname | name |
rolsuper | boolean |
rolinherit | boolean |
rolcreaterole | boolean |
rolcreatedb | boolean |
rolcanlogin | boolean |
rolreplication | boolean |
rolconnlimit | integer |
rolpassword | text |
rolvaliduntil | timestamp with time zone |
rolbypassrls | boolean |
rolconfig | text[] |
oid | oid |
假设您使用psycopg2
通过Python连接数据库,您可以对系统目录表执行查询:
import psycopg2
conn = psycopg2.connect(database="test", user='postgres')
cur = conn.cursor()
cur.execute('select * from pg_catalog.pg_user')
for row in cur.fetchall():
print(row)
cur.execute('select * from pg_catalog.pg_roles')
for row in cur.fetchall():
print(row)
答案 1 :(得分:0)
这是一个解决方案,它是通过将前一个程序的2个不同查询组合成一个基于SQL WHERE条件的单个查询得出的(假设你使用psycopg2用Python连接数据库)
import psycopg2
conn = psycopg2.connect(database="postgres", user='postgres')
cur = conn.cursor()
cur.execute('SELECT usename,rolname FROM pg_user,pg_roles WHERE oid=usesysid;')
#print ('users&roles')
for row in cur.fetchall():
print(row[0]+','+row[1])