【发布时间】:2020-02-01 19:17:18
【问题描述】:
在我的本地机器 (MacOS) 上,我有 MariaDB 10.4、Python 3.7.4 和 mysqlclient 1.4.4。 在远程服务器 (FreeBSD) 上,我有 MySQL 5.2、Python 3.7.2 和 mysqlclient 1.4.4。
数据库在两台机器上都采用utf8 编码。
我的脚本使用 CONCAT 查询,例如:
SELECT IF(agreements.date <> '0000-00-00', CONCAT(agreements.date, ' 00:00:00 +0300'), '').....
为什么在我的本地机器上,结果元组中的值始终是 STR,但在远程服务器上是 STR 或 BYTES 并且每个我使用 mysql 的 CONCAT 函数的列值以 b'...' 开头并具有 BYTES 类。 我知道我可以解码字节值 (b.decode()) 并保持其他 str 值不变
data = cursor.fetchall()
l = [list(x) for x in data]
for d in l:
for idx, vals in enumerate(d):
if isinstance(vals, bytes):
d[idx] = vals.decode()
但为什么会发生这种情况 - MySQL 版本??
我看到了两种方法:通过 Python 解码,或者使用 mysql 的 CONVERT <column> USING utf8 函数,正如 @Joe McKenna 所说。但是为什么我不应该在我不知道的本地计算机上执行此操作:( MySQL 服务器版本不同,但字符集配置相同。
示例脚本:
#!/usr/local/bin/python3
# coding: utf8
import MySQLdb
connection = MySQLdb.Connection(
user='root',
passwd='password',
db='billing',
host='localhost',
charset='utf8'
)
cursor = connection.cursor()
cursor.execute("SELECT '', CONCAT(birthdate, ' TEST!!!!!') from accounts")
for d in cursor.fetchall():
print(d)
cursor.close()
connection.close()
输出:
('', b'1958-11-11 TEST!!!!!')
('', b'0000-00-00 TEST!!!!!')
('', b'0000-00-00 TEST!!!!!')
('', b'0000-00-00 TEST!!!!!')
('', b'0000-00-00 TEST!!!!!')
('', b'0000-00-00 TEST!!!!!')
('', b'0000-00-00 TEST!!!!!')
('', b'0000-00-00 TEST!!!!!')
('', b'1950-10-09 TEST!!!!!')
更新:
mysql> SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';的结果
本地主机:
+--------------------------+--------------------+
| Variable_name | Value |
+--------------------------+--------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8mb4 |
| character_set_system | utf8 |
| collation_connection | utf8_general_ci |
| collation_database | utf8_general_ci |
| collation_server | utf8mb4_general_ci |
+--------------------------+--------------------+
远程服务器:
+--------------------------+-----------------+
| Variable_name | Value |
+--------------------------+-----------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| collation_connection | utf8_general_ci |
| collation_database | utf8_general_ci |
| collation_server | utf8_general_ci |
+--------------------------+-----------------+
【问题讨论】:
标签: python mysql unicode encoding