码迷,mamicode.com
首页 > 数据库 > 详细

Flask mysql

时间:2018-04-26 19:50:09      阅读:156      评论:0      收藏:0      [点我收藏+]

标签:flask   mysql   51cto   

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:123456@10.16.17.99: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=‘itmin@qq.com‘, 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

标签:flask   mysql   51cto   

原文地址:http://blog.51cto.com/tengxiansheng/2108273

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!