Python MySQL Tutorial – How to Create a Database Using Python

Last updated 5 months, 1 week ago | 455 views 75     5

Tags:- MySQL Python

When building a data-driven application, the first step is often creating a database. Python, paired with MySQL, makes this process smooth and efficient. In this tutorial, you’ll learn how to create a MySQL database programmatically using Python and the mysql-connector-python package.


Table of Contents

  1. What You Need

  2. Install MySQL Connector

  3. Connect to MySQL Server

  4. Create a MySQL Database

  5. Check if a Database Exists

  6. Handle Errors Gracefully

  7. Full Working Example

  8. Tips and Common Pitfalls


✅ What You Need

Before you begin, ensure the following:

  • Python 3 is installed

  • MySQL server is installed and running

  • You have MySQL user credentials

  • You’ve installed the MySQL Connector for Python (we’ll cover that next)


Step 1: Install MySQL Connector

Use pip to install the mysql-connector-python library:

pip install mysql-connector-python

This library allows Python to communicate with MySQL databases.


Step 2: Connect to MySQL Server

Before creating a database, you need to connect to the MySQL server:

import mysql.connector

mydb = mysql.connector.connect(
    host="localhost",
    user="your_username",
    password="your_password"
)

print("Connected to MySQL server!")

Replace "your_username" and "your_password" with your actual MySQL credentials.


Step 3: Create a New Database

Once connected, you can create a new database using a SQL CREATE DATABASE statement:

mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mytestdb")
print("Database created successfully.")

Step 4: Check If Database Exists

You can list all databases and check if one already exists:

mycursor.execute("SHOW DATABASES")

for db in mycursor:
    print(db)

✅ It's a good idea to check before creating a database to avoid errors.


Step 5: Handle Errors Gracefully

Wrap your code in a try-except block to catch connection or execution errors:

import mysql.connector
from mysql.connector import Error

try:
    mydb = mysql.connector.connect(
        host="localhost",
        user="your_username",
        password="your_password"
    )

    if mydb.is_connected():
        mycursor = mydb.cursor()
        mycursor.execute("CREATE DATABASE mytestdb")
        print("Database created successfully.")

except Error as e:
    print("Error:", e)

finally:
    if mydb.is_connected():
        mydb.close()
        print("Connection closed.")

 Complete Working Example

import mysql.connector
from mysql.connector import Error

def create_database(host, user, password, db_name):
    try:
        # Connect to MySQL server
        connection = mysql.connector.connect(
            host=host,
            user=user,
            password=password
        )

        # Create cursor and database
        cursor = connection.cursor()
        cursor.execute(f"CREATE DATABASE {db_name}")
        print(f"Database '{db_name}' created successfully.")

    except Error as err:
        print("Error:", err)

    finally:
        if connection.is_connected():
            connection.close()
            print("MySQL connection is closed.")

# Run function
create_database("localhost", "root", "your_password", "mytestdb")

⚠️ Common Pitfalls

Pitfall Solution
Access denied for user Ensure username/password is correct
Can't connect to MySQL server Make sure MySQL server is running
Database already exists Use SHOW DATABASES before creation
Not closing connection Use finally block or with statement

Tips

  • ✅ Use parameterized queries when working with user input

  • ✅ Always close your database connections

  • ✅ Use a try-except block to catch connection or SQL errors

  • ✅ Use lowercase, underscore-separated names for database naming consistency


Summary

Action Code
Install connector pip install mysql-connector-python
Connect to MySQL mysql.connector.connect()
Create database cursor.execute("CREATE DATABASE mydb")
Show databases cursor.execute("SHOW DATABASES")
Handle errors Use try-except block

Final Thoughts

Creating a MySQL database using Python is straightforward, thanks to the mysql-connector-python package. This foundational step allows you to build powerful applications that interact with structured data stored in MySQL. With proper error handling and clean connection management, your code will be more reliable and scalable.