python-mysqlHow do I show databases in MySQL using Python?
To show databases in MySQL using Python, you can use the show databases
command in the MySQLdb
package. This package is a Python interface for interacting with a MySQL server. To use this command, you must first establish a connection to the MySQL server.
import MySQLdb as mdb
con = mdb.connect('localhost', 'user', 'password', 'database')
cur = con.cursor()
cur.execute("show databases")
for x in cur:
print(x)
The above code will output a list of all the databases in the MySQL server:
('information_schema',)
('mysql',)
('mydb',)
('performance_schema',)
('sys',)
The code is composed of the following parts:
import MySQLdb as mdb
: This imports theMySQLdb
package and assigns it to the variablemdb
.con = mdb.connect('localhost', 'user', 'password', 'database')
: This establishes a connection to the MySQL server.cur = con.cursor()
: This creates a cursor object which will be used to execute commands.cur.execute("show databases")
: This executes theshow databases
command which retrieves a list of databases from the MySQL server.for x in cur:
: This iterates through the list of databases returned from theshow databases
command.print(x)
: This prints each database in the list of databases.
For more information, see the following links:
More of Python Mysql
- How can I connect Python to a MySQL database?
- How do I download MySQL-Python 1.2.5 zip file?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a cursor to interact with a MySQL database in Python?
- How do I use Python to connect to a MySQL database using XAMPP?
- How can I access MySQL using Python?
- How can I use Yum to install the MySQLdb Python module?
- How can I export data from a MySQL database to a CSV file using Python?
- How can I connect to MySQL using Python?
See more codes...