Create MySQL Database with Python Function

  • Share this:

Code introduction


This function is used to create a MySQL database. If the database already exists, it will not be created again.


Technology Stack : mysql-connector-python

Code Type : Function

Code Difficulty : Intermediate


                
                    
import mysql.connector
from mysql.connector import Error

def create_database(db_name):
    try:
        connection = mysql.connector.connect(
            host='localhost',
            user='your_username',
            password='your_password'
        )
        if connection.is_connected():
            cursor = connection.cursor()
            cursor.execute(f"CREATE DATABASE IF NOT EXISTS {db_name}")
            print(f"Database {db_name} created successfully")
    except Error as e:
        print("Error while connecting to MySQL", e)
    finally:
        if connection.is_connected():
            cursor.close()
            connection.close()