在用python做写数据库的客户端时, 发生了写入的中文数据为乱码的问题。经过查找资料,发现为客户端连接时的编码方式问题。
使用MySQLdb包。
问题如下图:
后来在连接数据库时,进行了编码方式的设置charset="utf8",就没问题了。代码段如下:
import MySQLdb
conn = MySQLdb.connect(
host = '192.168.1.20',
port = 3306,
user = 'root',
passwd = 'test',
db = 'test',
charset="utf8",
)
cur = conn.cursor()
for i in range(REGION_NUM):
mip = "0.0.0.%d"%(i)
region = code_to_region[i].split('_')
region_en = region[0]
operator_en = region[1]
region_cn = region_dict[region_en]
operator_cn = operator_dict[operator_en]
command = "INSERT INTO `test`.`qlljx_region` (`id`, `mip`, `region`, `province_en`, " \
"`province_cn`, `operator_en`, `operator_cn`) VALUES ('%d', '%s', '%s', '%s', '%s', '%s', '%s');" \
%(i, mip, code_to_region[i], region_en, region_cn, operator_en, operator_cn)
print command
cur.execute(command)
最后的结果如下图: