Python

Creating New Databases in MySQL Using Python

Creating New Databases in MySQL Using Python - Creating New Database 

Creating a New MySQL Database with Python

Databases are the backbone of any application. This guide shows you how to create a new MySQL database from Python ÔÇö list existing databases, create new ones, and verify success.

Complete Python Course:-
SQL Tutorial:-

Step 1: List Existing Databases

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="your_password"
)
cur = conn.cursor()

cur.execute("SHOW DATABASES")
for db in cur:
    print(db)

conn.close()

Step 2: Create a New Database

import mysql.connector

conn = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="your_password"
)
cur = conn.cursor()

try:
    cur.execute("CREATE DATABASE PythonDB2")
    print("Database created!")
except mysql.connector.Error as e:
    print("Error:", e)

conn.close()

Safer: CREATE IF NOT EXISTS

cur.execute("CREATE DATABASE IF NOT EXISTS PythonDB2")
# No error if it already exists

Step 3: Verify Creation

cur.execute("SHOW DATABASES")
for db in cur:
    print(db)
# PythonDB2 should appear in the list

Best Practices

  • Always close connections with conn.close().
  • Use try/except for graceful error handling.
  • Use IF NOT EXISTS for safe re-runs.
  • Never hardcode passwords ÔÇö use environment variables.
  • Use connection pools for production apps.

Modern Pattern: Context Manager

import mysql.connector
import os

with mysql.connector.connect(
    host="localhost",
    user="root",
    passwd=os.environ["MYSQL_PASS"]
) as conn:
    with conn.cursor() as cur:
        cur.execute("CREATE DATABASE IF NOT EXISTS PythonDB2")
        print("Done")

Download New Real Time Projects:- Click here

Conclusion

Creating a MySQL database from Python takes just a few lines. Use IF NOT EXISTS for safety and context managers for clean resource handling. For more guides, stay tuned to .

how to create a database mysql
how to create a database in sql
create database mysql command
creating new database in sql server
python mysql create database
mysql connector python
create database if not exists
python mysql tutorial

Source Code Available

Interested in This Project?

Get the complete source code for this project at a very affordable price — perfect for your portfolio, college submission, or learning. Message us on WhatsApp and we'll get back to you instantly!

Full source code included Step-by-step setup guide Instant delivery on WhatsApp Instant reply on WhatsApp
Chat on WhatsApp

We usually reply within a few minutes

Leave a Reply

Your email address will not be published. Required fields are marked *

Chat with us