简体   繁体   中英

How do I extract table metadata from a database using python

I want to come up minimal set of queries/loc that extracts the table metadata within a database , on as many versions of database as possible. I'm using PostgreSQl . I'm trying to get this using python . But I've no clue on how to do this, as I'm a python newbie.

I appreciate your ideas/suggestions on this issue.

You can ask your database driver, in this case psycopg2 , to return some metadata about a database connection you've established. You can also ask the database directly about some of it's capabilities, or schemas, but this is highly dependent on the version of the database you're connecting to, as well as the type of database.

Here's an example taken from http://bytes.com/topic/python/answers/438133-find-out-schema-psycopg for PostgreSQL :

>>> import psycopg2 as db
>>> conn = db.connect('dbname=billings user=steve password=xxxxx port=5432')
>>> curs = conn.cursor()
>>> curs.execute("""select table_name from information_schema.tables WHERE table_schema='public' AND table_type='BASETABLE'""")
>>> curs.fetchall()
[('contacts',), ('invoicing',), ('lines',), ('task',), ('products',),('project',)]

However, you probably would be better served using an ORM like SQLAlchemy . This will create an engine which you can query about the database you're connected to, as well as normalize how you connect to varying database types.

If you need help with SQLAlchemy , post another question here! There's TONS of information already available by searching the site.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM