个人博客地址:Python3连接MySQL并且读取Blob字段信息 | 一张假钞的真实世界
安装驱动
$ pip3 install mysql-connector-python
Command 'pip3' not found, but can be installed with:
sudo apt install python3-pip
根据提示信息安装pip3。
根据MySQL官网建议应该安装8.0的驱动。我的安装:mysql-connector-python-8.0.13、protobuf-3.6.1、setuptools-40.6.2、six-1.11.0。
读取MySQL数据
以读取Azkaban中的triggers表数据为例。代码如下:
#!/usr/bin/python3import mysql.connector
import gzipconfig = {'user': 'roHive','password': 'hive@bigdata!23','host': '172.16.72.22','database': 'azkaban3','raise_on_warnings': True,'charset': 'latin1'
}cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
query = ("SELECT trigger_id, data FROM azkaban3.triggers")
cursor.execute(query)for (triggerId, triggerData) in cursor:print(f'triggerId={triggerId}')cursor.close()
cnx.close()
Azkaban的triggers表中的data字段是BLOB类型。因为我的Azkaban MySQL库采用的是latin1编码,如果连接时不设置字符集在读取data字段数据时在读取BLOB类型字段时会报如下错误:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
因为data字段是采用gzip压缩的,所以需要解压,代码如下:
for (triggerId, triggerData) in cursor:print(gzip.decompress(bytes(triggerData, encoding='latin1')))