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 EXISTSfor 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