Flask mysql
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask mysql相关的知识,希望对你有一定的参考价值。
1、install flask-sqlalchemy and mysql-python
pip3 install flask-sqlalchemy
pip3 install pymysql
2、生成数据库
vs ide保存时报错,忽略试试是否可执行
app = Flask(__name__)
app.config[‘SECRET_KEY‘] = ‘haha‘
app.config[‘SQLALCHEMY_DATABASE_URI‘] = ‘mysql+pymysql://wiki_w:[email protected]:3499/flaskr‘
app.config[‘SQLALCHEMY_TRACK_MODIFICATIONS‘] = True #设置这一项是每次请求结束后都会自动提交数据库中的变动
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(320), unique=True)
phone = db.Column(db.String(32), nullable=False)
def __init__(self, username, email, phone):
self.username = username
self.email = email
self.phone= phone
if __name__ == ‘__main__‘:
db.drop_all()
db.create_all()
3、插入、查询、更新、删除数据库
## 插入
...........
inset=User(username=‘itmin‘, email=‘[email protected]‘, phone=‘13812345678‘)
db.session.add(inset)
db.session.commit()
## 更新
..............
news=User.query.all()
print news
news[1].username=‘test‘
db.session.commit()
## 删除
name=User.query.filter_by(username = ‘bb‘).first()
db.session.delete(name)
db.session.commit()
## 查询
1、精确匹配
select_=User.query.filter_by(username=‘itmin‘).first()
print(select_.id)
2、模糊匹配
query = User.query.filter(User.email.endswith(‘@qq.com‘)).all()
print(query)
3、反向查询
query = User.query.filter(User.username != ‘yoyo‘).first()
print(query)
4、或查询
query = User.query.filter(or_(User.username != ‘yoyo‘, User.email.endswith(‘@example.com‘))).first()
print(query)
5、与查询
query = User.query.filter(and_(User.username != ‘yoyo‘, User.email.endswith(‘@example.com‘))).first()
print(query)
6、查询返回数据的数目
num = User.query.limit(10).all()
print(num)
7、查询全部
data_all = User.query.all()
print(data_all)
for i in range(len(data_all)):
print(data_all[i].username+" "+data_all[i].email+" "+data_all[i].phone)
以上是关于Flask mysql的主要内容,如果未能解决你的问题,请参考以下文章