Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 813
jerrymouse Avatar asked Feb 15 '12 15:02

jerrymouse


3 Answers

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?

like image 182
t00ny Avatar answered Nov 20 '22 13:11

t00ny


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

conn.info.dbname
like image 43
Michael Grazebrook Avatar answered Nov 20 '22 14:11

Michael Grazebrook


for postgresql:-

cursor.execute("select current_database()")
db_name = cursor.fetchone()[0]
like image 2
LightSith Avatar answered Nov 20 '22 14:11

LightSith