python开发之web篇-flask框架操作mysql数据库

一  数据库连接

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
# import pymysql

app = Flask(__name__)

# 配置flask配置对象中键:SQLALCHEMY_DATABASE_URI
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:123456@localhost/pythonstudy"

# 配置flask配置对象中键:SQLALCHEMY_COMMIT_TEARDOWN,设置为True,应用会自动在每次请求结束后提交数据库中变动
app.config['SQLALCHEMY_COMMIT_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True

# 获取SQLAlchemy实例对象,接下来就可以使用对象调用数据
db = SQLAlchemy(app)

二  创建模型

# 创建模型对象
class User(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True)
    user_name = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)


def __repr__(self):
 return '' % self.username

三 实现增删改查

@app.route('/userList')
def user_list():
    # user_list = User.query.all()
    user_list = User.query.order_by(User.id).all()
    return render_template("user.html", user_list=user_list)


@app.route('/user_add')
def user_add():
    u1 = User(user_name='zbz', email='[email protected]')
    u2 = User(user_name='wzx', email='[email protected]')

    db.session.add(u1)
    db.session.add(u2)
    db.session.commit()

    return "OK"


@app.route('/user_delete')
def user_delete():
    user = User.query.filter_by(id=1).first()
    db.session.delete(user)
    db.session.commit()

    return "OK"


@app.route('/user_update')
def user_update():
    user = User.query.filter_by(id=2).first()
    user.email = "[email protected]"
    db.session.commit()
    return "ok"

其他参考:https://www.cnblogs.com/lonelyhiker/p/8486221.html

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