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)