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 can I use Python to interact with a MySQL database using YAML?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I use the MySQL Connector in Python?
- How do I create a Python script to back up my MySQL database?
- How do I use a Python variable in a MySQL query?
- How can I use Python and MySQL to generate a PDF?
See more codes...