jerrymouse
jerrymouse

Reputation: 17792

How to get database name from postgres/mysql cursor object

I have a several postgres and mysql cursor objects exposed to me, created in some universe. How to find the database name (and other info about that db) from these cursor objects?

cursor.__dict__ gives nothing useful.

Upvotes: 7

Views: 8236

Answers (3)

Michael Grazebrook
Michael Grazebrook

Reputation: 5671

If you also have the connection (call it conn):

conn.info.dbname

Upvotes: 5

LightSith
LightSith

Reputation: 917

for postgresql:-

cursor.execute("select current_database()")
db_name = cursor.fetchone()[0]

Upvotes: 2

t00ny
t00ny

Reputation: 1648

I don't know about postgres but using MySQLdb you could always use the following:

cursor.execute("select database()")
db_name = cursor.fetchone()[0]

Maybe there's a cleaner way to do this...

Edit:

for other info it depends on what exactly you're looking for but for example to fetch table names

cursor.execute("show tables")
for r in cursor.fetchall():
    print r[0]

There are many other functions available... Is there anything specific you're looking for?

Upvotes: 4

Related Questions