To check if a database exists in MySQL using Python, you can use the `
mysql-connector-python
` module which provides a Python interface to
MySQL.
Here's an example Python program that checks if a database exists in
MySQL :
import mysql.connector
# Create a connection to the MySQL server
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
# Create a cursor object to execute SQL statements
mycursor = mydb.cursor()
# Check if a database exists
mycursor.execute("SHOW DATABASES")
databases = mycursor.fetchall()
database_exists = False
for database in databases:
if 'mydatabase' in database:
database_exists = True
break
if database_exists:
print("Database exists")
else:
print("Database does not exist")​