连接mysql数据库测试(专业版)
[注意1:要导入text库,否则可能出现找不到select 1错误]
[注意2:若出现下列问题,可按照模板代码的顺序db = SQLAlchemy(app) 的位置]
RuntimeError: Either 'SQLALCHEMY_DATABASE_URI' or 'SQLALCHEMY_BINDS' must be set.
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
app = Flask(__name__)# MySQL所在主机名,默认127.0.0.1
HOSTNAME = "127.0.0.1"
PORT = 3306
USERNAME = "root"
PASSWORD = "****"
DATABASE = "***"
app.config['SQLALCHEMY_DATABASE_URI'] = f"mysql+pymysql://{USERNAME}:{PASSWORD}@{HOSTNAME}:{PORT}/{DATABASE}?charset=utf8"db = SQLAlchemy(app)with app.app_context():with db.engine.connect() as conn:result = conn.execute(text("select 1"))print(result.fetchone()) # (1,)
ORM的实现
class User(db.Model):__tablename = 'admin'id = db.Column(db.Integer,primary_key=True,autoincrement=True)sname = db.Column(db.String(100),nullable=False)snumber = db.Column(db.String(100),nullable=False)address = db.Column(db.String(100),nullable=False)with app.app_context():db.create_all()
命令行的实现及结果
mysql> show tables;
+---------------+
| Tables_in_flk |
+---------------+
| admin |
| user |
+---------------+
2 rows in set (0.00 sec)mysql> desc admin;
+---------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| sname | varchar(100) | NO | | NULL | |
| snumber | varchar(100) | NO | | NULL | |
| address | varchar(100) | NO | | NULL | |
+---------+--------------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
ORM插入实现
user = User(sname='pass', snumber=10, address='163@qq.com')
db.session.add(user)
db.session.commit()
mysql> select * from admin;
+----+-------+---------+------------+
| id | sname | snumber | address |
+----+-------+---------+------------+
| 1 | pass | 10 | 163@qq.com |
+----+-------+---------+------------+
1 row in set (0.00 sec)
ORM查询实现
user = User.query.get(1)
print(user.sname)
# 输出 pass
ORM筛选实现
user = User.query.filter_by(sname='pass')
print(user[0].address)
# 输出 163@qq.com
ORM更新实现
user = User.query.filter_by(sname='pass').first()
user.address = '666@qq.com'
db.session.commit()
ORM删除实现
user = User.query.get(1)
db.session.delete(user)
db.session.commit()
其他待更新中。。。