To use Flask and SQLAlchemy to connect to a MySQL database:
Install Flask and SQLAlchemy libraries.
Import Flask and SQLAlchemy libraries in the Python code.
Define the Flask app object.
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://<username>:<password>@<host>/<database>'
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(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
db.create_all()
user = User(username='john', email='john@example.com')
db.session.add(user)
db.session.commit()
users = User.query.all()
user = User.query.filter_by(username='john').first()
user.email = 'newemail@example.com'
db.session.commit()
user = User.query.filter_by(username='john').first()
db.session.delete(user)
db.session.commit()
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-12-15 11:00:00 +0000
Seen: 19 times
Last updated: Dec 05 '22
What is the process of developing two databases in a Django application using docker-compose?
How can a web application be developed to send distinct emails upon clicking the SUBMIT button?
How can multiple queries be merged into a single stored procedure in MySQL?
What does "waiting for handler commit" mean in relation to the slow writes experienced in MySQL 8?
How can Spring Boot and Mysql be utilized for CRUD operations?
What is the method to retrieve the JSON data from a column in SQL?
How can I use sqlalchemy to merge JSON within a column of mysql?
Retrieve all rows in which two IDs appear for the first time.