在学习 Python3 爬虫关系型数据库储存时,利用 pymysql 连接 MySQL 建表,测试用的代码如下,第一句 SQL 用于获取当前 MySQL 的版本信息,第二句 SQL 执行创建 spiders 数据库的操作,如果程序代码正确,将会输出 MySQL 的版本信息,并且能查询到 spiders 数据库的存在

import pymysql

db = pymysql.connect(host='localhost', user='root', password='000000', port=3306)
cursor = db.cursor()
cursor.execute('SELECT VERSION()')
data = cursor.fetchone()
print('Database version:', data)
cursor.execute("CREATE DATABASE spiders DEFAULT CHARACTER SET utf8")
db.close()

运行程序,确实输出了 MySQL 的版本信息:Database version: ('8.0.17',),但同时还出现了以下警告:

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.")
  result = self._query(query)

先查询一下 spiders 数据库是否已经创建成功,使用 mysql -u root -p 命令登录 MySQL,使用 show databases 命令可以查看到 spiders 数据库已经存在,说明创建成功
01
然而程序员是讲究严谨的,即便是已经实现了数据库的创建,但警告信息同样也不能放过,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.") 大致看一下应该是编码上的问题,百度翻译一下该警告信息:警告:(3719,“utf8”当前是字符集utf8mb3的别名,但在将来的版本中将是utf8mb4的别名。请考虑使用utf8mb4,以便不含糊。”)

解决办法:将代码中的 utf8 改为 utf8mb4 后再次运行就没有警告了!

原理分析:百度了一下,MySQL 中的 utf8 就是 utf8mb3,最大兼容三字节的 unicode 字符,MySQL 在 5.5.3 版本之后增加了 utf8mb4 的编码,mb4 就是 most bytes 4 的意思,专门用来兼容四字节的 unicode 字符,utf8mb4 是 utf8mb3 的超集,utf8mb3 和 utf8mb4 表示的范围如下表:

说明mysql utf8 / utf8mb3mysql utf8mb4
max bit34
范围基本多文种平面 + US-ASCII辅助平面(Supplementary) + 基本多文种平面 + US-ASCII
unicode范围U+0000 - U+FFFFU+0000 - U+10FFFFF
常见字符英文字母,CJK大部分常用字等CJK非常用字,数学符号,emoji表情等
Logo

更多推荐