pip3 install flask-sqlalchemy
pip3 install pymysql
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()
## 插入
...........
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)
原文地址:http://blog.51cto.com/tengxiansheng/2108273