Add, delete, modify and check the MySQL database in the flask framework

The following is a simple sample code that can use the SQLAlchemy library in Flask to implement addition, deletion, modification and query of the MySQL database:

from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbname'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    email = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(50))

    def __init__(self, name, email, password):
        self.name = name
        self.email = email
        self.password = password

@app.route('/users', methods=['POST'])
def create_user():
    data = request.get_json()
    name = data['name']
    email = data['email']
    password = data['password']
    new_user = User(name, email, password)
    db.session.add(new_user)
    db.session.commit()
    return jsonify({
    
    'message': 'User created successfully!'})

@app.route('/users', methods=['GET'])
def get_users():
    users = User.query.all()
    output = []
    for user in users:
        user_data = {
    
    }
        user_data['id'] = user.id
        user_data['name'] = user.name
        user_data['email'] = user.email
        user_data['password'] = user.password
        output.append(user_data)
    return jsonify({
    
    'users': output})

@app.route('/users/<id>', methods=['GET'])
def get_user(id):
    user = User.query.get(id)
    if not user:
        return jsonify({
    
    'message': 'User not found!'})
    user_data = {
    
    }
    user_data['id'] = user.id
    user_data['name'] = user.name
    user_data['email'] = user.email
    user_data['password'] = user.password
    return jsonify({
    
    'user': user_data})

@app.route('/users/<id>', methods=['PUT'])
def update_user(id):
    user = User.query.get(id)
    if not user:
        return jsonify({
    
    'message': 'User not found!'})
    data = request.get_json()
    user.name = data['name']
    user.email = data['email']
    user.password = data['password']
    db.session.commit()
    return jsonify({
    
    'message': 'User updated successfully!'})

@app.route('/users/<id>', methods=['DELETE'])
def delete_user(id):
    user = User.query.get(id)
    if not user:
        return jsonify({
    
    'message': 'User not found!'})
    db.session.delete(user)
    db.session.commit()
    return jsonify({
    
    'message': 'User deleted successfully!'})

if __name__ == '__main__':
    app.run(debug=True)

In the sample code above, we defined a Userdata model called , and then created five routes in Flask, which are used to create users, get all users, get a single user, update users, and delete users. In each route, we use SQLAlchemy to operate on the database. It should be noted that when using SQLAlchemy, we need to define the database connection information and data model in the Flask application first.

Using the MySQL cursor can also directly execute SQL commands to add, delete, modify, and query the MySQL database. The following is a simple sample code that can use the MySQL cursor to implement addition, deletion, modification and query of the MySQL database:

import mysql.connector

# 连接 MySQL 数据库
mydb = mysql.connector.connect(
    host="localhost",
    user="username",
    password="password",
    database="dbname"
)

# 创建 MySQL cursor
mycursor = mydb.cursor()

# 插入数据
sql = "INSERT INTO users (name, email, password) VALUES (%s, %s, %s)"
val = ("John", "[email protected]", "password123")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")

# 查询数据
mycursor.execute("SELECT * FROM users")
myresult = mycursor.fetchall()
for x in myresult:
    print(x)

# 更新数据
sql = "UPDATE users SET name = %s WHERE email = %s"
val = ("Mike", "[email protected]")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) updated")

# 删除数据
sql = "DELETE FROM users WHERE email = %s"
val = ("[email protected]",)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")

In the sample code above, we first connected to the MySQL database and then created a MySQL cursor object. Next, we can use execute()functions to execute SQL commands, such as inserting data, querying data, updating data, and deleting data, etc. It should be noted that after executing the SQL command, we need to use commit()the function to commit the changes of the transaction.

Guess you like

Origin blog.csdn.net/weixin_42499608/article/details/131428153