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 theMySQLdbpackage 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 databasescommand which retrieves a list of databases from the MySQL server.for x in cur:: This iterates through the list of databases returned from theshow databasescommand.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 create a web application using Python and MySQL?
- How can I access MySQL using Python?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How can I use Python and MySQL to generate a PDF?
- How do I connect Python with MySQL using XAMPP?
- How do I insert JSON data into a MySQL database using Python?
- How can I connect Python and MySQL?
- How do I connect to XAMPP MySQL using Python?
- How can I use Yum to install the MySQLdb Python module?
See more codes...