flask Sqlalchemy数据库操作

from flask import Flask
from flask_script import Manager
from flask_sqlalchemy import SQLAlchemy

app = Flask(name)
app.config[‘SQLALCHEMY_DATABASE_URI’] = ‘mysql+pymysql://root:[email protected]:3306/python1807’ #配置链接数据库的地址
app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS’] = False
db = SQLAlchemy(app)
manager = Manager(app)

#创建模型
class User(db.Model):
id = db.Column(db.Integer,primary_key=True)
username = db.Column(db.String(20),index=True)
sex = db.Column(db.Boolean,default=True)
age = db.Column(db.Integer,default=20)

@app.route(’/create_table/’)
def create_table():
db.create_all()
return ‘创建表’

@app.route(’/drop_table/’)
def drop_table():
db.drop_all()
return ‘删除表’

#添加一条数据
@app.route(’/insert_one/’)
def insert_one():
u = User(username=‘张三’,sex=False,age=18)
db.session.add(u)
db.session.commit()
return ‘insert_one’

#添加多条数据
@app.route(’/insert_many/’)
def insert_many():
try:
u1 = User(username=‘李四’)
u2 = User(username=‘王五’)
db.session.add_all([u1,u2])
db.session.commit()
except:
db.session.rollback()
return ‘insert_many’

#查询
@app.route(’/select/’)
def select():
u = User.query.get(1)
# print(u)
print(u.username)
print(u.sex)
print(u.age)
return ‘查询id值’

#修改
@app.route(’/update/’)
def update():
u = User.query.get(1)
u.username = ‘张三123’
u.age = 30
db.session.add(u)
db.session.commit()
return ‘修改’

#删除
@app.route(’/delete/’)
def delete():
u = User.query.get(1)
db.session.delete(u)
db.session.commit()
return ‘删除’

if name ==‘main’:
manager.run()

你可能感兴趣的:(自我学习)