Python, Flask, MYSQL - Basics - Demo
Here's a step-by-step guide to set up MySQL using XAMPP, create a database, and run your Flask + SQLAlchemy app using the .env
-based setup.
✅ Step 1: Install and Run XAMPP
-
Download XAMPP from https://www.apachefriends.org/index.html.
-
Install XAMPP on your system.
-
Open the XAMPP Control Panel.
-
Start Apache and MySQL modules.
-
Green indicators mean they are running.
-
✅ Step 2: Open phpMyAdmin & Create Database
-
Go to your browser and open:
http://localhost/phpmyadmin -
Click on Databases tab.
-
In the "Create database" field, type:
phd
(or your DB name). -
Click Create.
Done! Your MySQL DB is ready.
✅ Step 3: Create .env
File in Flask Project
In your Flask project directory, create a file named .env
:
DB_USERNAME=root
DB_PASSWORD=
DB_HOST=localhost
DB_PORT=3306
DB_NAME=phd
-
XAMPP default MySQL username is
root
-
Password is usually empty (set it in phpMyAdmin if you want)
✅ Step 4: Install Required Python Packages
Make sure your virtual environment is activated, then run:
pip install flask flask_sqlalchemy python-dotenv pymysql
✅ Step 5: Create Your Flask App
Here's a minimal working example for app.py
:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from dotenv import load_dotenv
import os
load_dotenv()
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = (
f"mysql+pymysql://{os.getenv('DB_USERNAME', 'root')}:"
f"{os.getenv('DB_PASSWORD', '')}@"
f"{os.getenv('DB_HOST', 'localhost')}:"
f"{os.getenv('DB_PORT', '3306')}/"
f"{os.getenv('DB_NAME', 'phd')}"
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
# Example model
class Student(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100))
with app.app_context():
db.create_all()
@app.route('/')
def home():
return "Database connected and tables created!"
if __name__ == '__main__':
app.run(debug=True)
✅ Step 6: Run Your Flask App
In the terminal (inside the Flask project directory):
python app.py
Open a browser and go to:
http://127.0.0.1:5000/
You should see:
Database connected and tables created!
✅ Step 7: (Optional) Check Tables in phpMyAdmin
-
Click the
phd
database. -
You should see the
student
table created bydb.create_all()
.
π Pro Tip: Add .env
to .gitignore
If you're using Git:
echo ".env" >> .gitignore
This prevents your credentials from being tracked in version control.
Let me know if you'd like to add forms, insert data, or query records!
Comments
Post a Comment