携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第7天,点击查看活动详情
基本连接
1.python环境安装依赖
pip install flask
pip install flask-sqlalchemy
pip install pymysql
2.开放本地mysql端口
我使用的是本地的mac版本的mysql服务器,而python环境使用的是远程虚拟环境,两者不在一块,涉及到跨域连接,因此需要开放端口,开放我本地的3306(mysql端口,看自己情况选择)端口给外部使用,mac开放端口的操作如下:
偏好设置 --> 共享 --> 远程apple事件
3.在pycharm中创建config.py文件,用于设置flask连接mysql的一些参数
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://用户名:密码@ip:端口号/数据库名"
SQLALCHEMY_COMMIT_ON_TEARDOWN = False
4.在app.py中初始化db并使用
from flask import Flask
import config
app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
至此边可以成功连接数据库并对其进行操作了
基本操作
首先创建一个model实体类
class Students(db.Model):
__tablename__ = 'students'
id = db.Column(db.Integer, primary_key = True)
name = db.Column(db.String(16))
stu_number = db.Column(db.String(16))
def __repr__(self):
return '<Students: %s %s %s>' % (self.id, self.name, self.stu_number)
CRUD操作
def create_table():
db.drop_all()
db.create_all()
stu1 = Students(name='占三', stu_number='1')
stu2 = Students(name='里斯', stu_number='2')
stu3 = Students(name='王武', stu_number='3')
# 添加多个对象
db.session.add_all([stu1, stu2, stu3])
db.session.commit() # 添加完成之后一定要commit()
# 删除一个对象
db.session.delete(stu2)
db.session.commit() # 删除完成之后要commit()
# 更新用户
# 首先找到需要修改的那一条记录
stu = Students.query.first()
stu.name = '王三' # 设置完修改的数据之后,直接commit就可以,不需要额外的add操作
db.session.commit()
# 查询操作
students = Students.query.all()
常见错误
is not allowed to connect to this MySQL server
pymysql.err.OperationalError: (1130, “xxx‘ is not allowed to connect to this MySQL server“)
解决办法:更改数据库localhost的权限,具体操作如下:
mysql -uroot -p #登录数据库
输入下面的命令:
use mysql;
select host,user from user; #查看数据库的权限信息
结果如下:
可以看到localhost具有root权限,因此需要更改权限
update user set host = '%' where user ='root'; #修改权限
flush privileges;#刷新
RuntimeError: 'cryptography'
RuntimeError: 'cryptography' package is required for sha256_password or caching_sha2_password auth methods
解决办法:安装依赖即可
pip install cryptography