python之SQLAlchemy实现数据库增删查改操作

首先查看自己相关的包是否安装。

在这里插入图片描述
在这里插入图片描述
以下给上代码:
这里的代码是数据配置的一些相关信息
flask_sql.py

DIALECT = 'mysql'
DRIVER = 'pymysql'
USERNAME = 'root'
PASSWORD = '123456'
HOST = '127.0.0.1'
PORT = '3306'
DATABASE = 'flask_test'
SQLALCHEMY_DATABASE_URI = '{}+{}://{}:{}@{}:{}/{}?charset=utf8mb4'.format(
DIALECT, DRIVER, USERNAME, PASSWORD, HOST, PORT, DATABASE
)
SQLALCHEMY_TRACK_MODIFICATIONS = False #关闭动态跟踪
SQLALCHEMY_ECHO = True #查询时回显


通过调用flask_sql.py文件获取数据库的相关配置信息。
Book是我新建的一个表,然后进行创表实现增删查改。
flask_testsql.py

from datetime import datetime
from flask import Flask
import App.sqltest.flask_sql
from flask_sqlalchemy import SQLAlchemy
app=Flask(__name__)
app.config.from_object(App.sqltest.flask_sql)
db=SQLAlchemy(app)

class Book(db.Model):
    __tablename__="book"
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    title = db.Column(db.String(50),nullable=False) #书名
    publishing_office = db.Column(db.String(100),nullable=False)
    isbn = db.Column(db.String(100),nullable=False)
    storage_time = db.Column(db.DateTime,default=datetime.now())
@app.before_first_request #使用钩子函数
def first_request():
    db.create_all()
#
@app.route("/add")
def add():
    book1=Book(title="追风筝的人",publishing_office="XX出版社",isbn="100",storage_time="2020-01-01")
    book2 = Book(title="摆渡人",publishing_office="XX出版社",isbn="100",storage_time="2020-01-01")
    db.session.add(book1)
    db.session.add(book2)
    db.session.commit()
    return "添加成功"
@app.route("/select")
def select():
    books=Book.query.filter(Book.id==3).first()
    print(books.title,books.publishing_office,books.isbn,books.storage_time)
    return "查询成功"
@app.route("/update")
def update():
    books=Book.query.filter(Book.id==3).first()
    books.title="python"
    bookes = Book.query.filter(Book.id == 3).first()
    print(bookes.title,bookes.publishing_office,bookes.isbn,bookes.storage_time)
    db.session.commit()
    return "修改成功"
@app.route("/delete")
def delete():
    books=Book.query.filter(Book.id==3).first()
    db.session.delete(books)
    db.session.commit()
    return "删除成功"
@app.route("/")
def hello_world():
    return "hello"
if __name__ == '__main__':
    app.run(debug=True)

你可能感兴趣的:(python,flask)