How to Check If a Database Exists By Listing All Databases in Python


In this example, we will learn how to check if a database exists by listing all databases in your system in Python.

Source Code

import mysql.connector

# connect to server
mydb = mysql.connector.connect(
    host="localhost",
    port=3306,
    user="yourusername",
    password="yourpassword"
)

# get a cursor
mycursor = mydb.cursor()

# execute a query
mycursor.execute("SHOW DATABASES")

for item in mycursor:
    print(item)

Output:

('information_schema',)
('mydatabase',)
('mysql',)
('performance_schema',)
('phpmyadmin',)
('python',)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement