- 安装对应模块
pip3 install flask-sqlalchemy mysql-connector
- 安装mysql
详见: mysql安装方式
mysql配置项 | 信息 |
---|---|
IP | 127.0.0.1 |
port | 3306 |
user | root |
password | 123456 |
databases | flask_test |
tables | user_info |
user_info
列user_id
,user_name
- 示例脚本
vim flask_mysql.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# python_version : python 3.7
# Author : taoyx
# Email : taoyx@taoyx.cc
import uuid
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
def uuid_demo():
uuid_4 = uuid.uuid4()
uuid_id = ''.join(str(uuid_4).split('-'))
return uuid_id
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ='mysql+mysqlconnector://root:123456@127.0.0.1:3306/flask_test?charset=utf8'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)
class user_info(db.Model):
__tablename__ = 'user_info'
user_id = db.Column('user_id', db.Integer, primary_key=True, unique=True, nullable=True)
user_name = db.Column(db.String(255), unique=True, nullable=True)
def __init__(self, user_id, user_name):
self.user_id = user_id
self.user_name = user_name
def __repr__(self):
return "{'user_id':'%s', 'user_name':'%s'}" % (self.user_id, self.user_name)
# 插入新数据
add_user = user_info(uuid_demo(), 'xiaoming')
db.session.add(add_user)
db.session.commit()
# 查询全部数据,并按照`user_name`列倒序查询
#xa = db.session.query(user_info).all()
xa = user_info.query.order_by(user_info.user_name.desc()).all()
print(xa)
# 查询指定数据,并按照`user_name`列倒序查询,并从第2条开始,查询共计5条数据
#x = db.session.query(user_info).filter(getattr(user_info, 'user_name') == 'xiaoming').with_entities(user_info.user_id, user_info.user_name).first()
#x = db.session.query(user_info).filter(user_info.user_name == 'xiaoming').first()
x = host_info.query.filter(user_info.user_name == 'xiaoming').order_by(user_info.user_name.desc()).offset(2).limit(5).all()
print(x)
# 查询模糊数据,并按照`user_name`列倒序查询,并从第2条开始,查询共计5条数据
# 与'like'相比,'ilike'忽略大小写
#x = db.session.query(user_info).filter(user_info.user_name == 'xiaoming').first()
x = host_info.query.filter(user_info.user_name.ilike('xiao%')).order_by(user_info.user_name.desc()).offset(2).limit(5).all()
print(x)
# 更新数据
#updata_user = db.session.query.filter(user_info.user_name == 'xiaoming').first()
updata_user = host_info.query.filter(user_info.user_name == 'xiaoming').first()
updata_user.user_name = 'xiaohong'
db.session.commit()
# 删除数据
del_user = host_info.query.filter(user_info.user_name == 'xiaohong').all()
db.session.delete(del_user)
db.session.commit()