Python 连接 MySQL 数据库及用法
前言
Python 可以通过符合 DBAPI 规范设计的框架(库)可操作 MySQL 数据库。比如:PyMySQL、mysqlclient等
PyMySQL
安装
1 | pip3 install PyMySQL |
卸载
1 | pip3 uninstall PyMySQL |
用法
纯用法:1
2
3
4
5
6self.dbcon = pymysql.connect(host='localhost',
user='root',
password='devhitao',
db='blog',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
SQLAlchemy 配置:1
2
3
4# dialect+driver://username:password@host:port/database
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:devhitao@localhost:3306/blog?charset=utf8mb4"
db = SQLAlchemy(app)
FQA
Q1:
site-packages/pymysql/cursors.py:170: Warning: (3719, “‘utf8’ is currently an alias for the character set UTF8MB3, but will be an alias for UTF8MB4 in a future release. Please consider using UTF8MB4 in order to be unambiguous.”)
A1:连接数据库时指定编码,比如 ?charset=utf8mb4 :1
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:devhitao@localhost:3306/sms?charset=utf8mb4"
参考资料
文档信息
- 版权声明:自由转载-保持署名-非商用-非衍生 ( CC BY-NC-ND 4.0 )