Python3连接MySQL并且读取Blob字段信息

安装驱动

1
2
3
$ 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表数据为例。代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/usr/bin/python3

import mysql.connector
import gzip

config = {
'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类型字段时会报如下错误:

1
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

因为data字段是采用gzip压缩的,所以需要解压,代码如下:

1
2
for (triggerId, triggerData) in cursor:
print(gzip.decompress(bytes(triggerData, encoding='latin1')))