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 do I use Python to authenticate MySQL on Windows?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I use Python to interact with a MySQL database using YAML?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How can I use Python to yield results from a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to update multiple columns in a MySQL database?
- How can I resolve the "no database selected" error when using Python and MySQL?
- How do I connect Python with MySQL using XAMPP?
See more codes...