Jan 17, 2023 Python

Flask-SQLAlchemy: DB Connection & Create table in MySQL

If you don't know how to use SQLalchemy with your Flask application, this tutorial will definitely gonna help you.
In this tutorial, I going to show you how to create a simple database in MySQL and add a new table with SQL comments using SQLalchemy.
Flask SQLAlchemy create MySQL tablePin
Why do People choose SQL Alchemy to create and manage the app database?
SQLAlchemy provides an interface for creating and executing database code without needing to write SQL statements.

How to Create DB Connection & Create a table in MySQL

Step 1: First, open phpMyadmin (In your Xamp or Wamp server and create a database named “sqlalchemy”.
Step 2: Create a main.py file and add the following file
First, install Flask SQLAlchemy using the following code.
pip install Flask-SQLAlchemy
Then, create a main.py  file and add the following code.
from flask import Flask

from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:''@localhost/alchemy'


db = SQLAlchemy(app)

class User(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    username = db.Column(db.String(80), unique = True)

    email = db.Column(db.String(80), unique = True)

    def __init__(self, username, email):

        self.username = username

        self.email = email

Explanation of this code:-

Configuration keys to connect your MySql database  with SQLAlchemy is
Use Model class to perform CRUD operation on the table.
Step 3: After writing this code, open the Python code folder in the terminal.
Then type
from main import db
Now go back to the Phpmyadmin and check the database. A new table named “User” will be created with 3 columns names (Id, username, email).
If you want to create another table,  just change the table name “user” with a new name like “employee” in class.
class Employee(db.Model):
Open the New terminal, and type
Then type
from main import db
Now check your Php Myadmin database.  A new table named “Employee” will be created.
Reference: Youtube Video

Share to...