Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of MySQL databases with python

I'm trying to get the names of all databases associated with my MySQL server via python (2.7), but am instead just getting the number of databases.

I looked around, and it seems like the only answer may be to use sys for a command line call, get the name of the databases, and proceed from there, but I can't believe that's the only way.

Current Code:

import MySQLdb

serv = MySQLdb.connect(host = "localhost", user = "root", passwd = "abcdefg")

c = serv.cursor()

print c.execute("SHOW DATABASES")

Output:

4

Thanks in advance for the help.

like image 843
elPastor Avatar asked Jul 03 '17 20:07

elPastor


People also ask

How do I get a list of databases in MySQL?

1. Open the Command Prompt and navigate to the bin folder of your MySQL Server installation directory. Then connect to the server using the mysql -u root -p command. Enter the password and execute the SHOW DATABASES; command we have discussed above.

How do I query a MySQL database in Python?

To query data in a MySQL database from Python, you need to do the following steps: Connect to the MySQL Database, you get a MySQLConnection object. Instantiate a MySQLCursor object from the the MySQLConnection object. Use the cursor to execute a query by calling its execute() method.


1 Answers

I am not sure if mysql connector is same as your library, but using msyql connector your answer would be something like this:

import mysql.connector
conn = mysql.connector.connect (user='user', password='password',
                               host='server_address',buffered=True)
cursor = conn.cursor()
databases = ("show databases")
cursor.execute(databases)
for (databases) in cursor:
     print databases[0]
like image 137
Iman Mirzadeh Avatar answered Sep 23 '22 10:09

Iman Mirzadeh