Google News
logo
Python Program to Check if a database exist
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")​
In this example, the `mysql.connector` module is imported at the beginning of the program. The `connect()` function is then called to create a connection to the MySQL server. You will need to replace `yourusername` and `yourpassword` with your MySQL username and password.

Next, a cursor object is created using the `cursor()` method of the connection object. This cursor object can be used to execute SQL statements on the database.

In this example, the program executes a `SHOW DATABASES` statement to get a list of all databases on the MySQL server. The `fetchall()` method is then called to fetch all the results of the query as a list of tuples.

The program then loops through the list of databases and checks if the database `mydatabase` exists. If the database exists, the program sets the variable `database_exists` to `True`. Otherwise, the variable is set to `False`.

Finally, the program prints a message indicating whether the database exists or not.