pymssql查询结果中文乱码处理
乱码原因
- 乱码的地方加上.encode(‘latin1’).decode(‘gbk’),先编码成SQL server支持的编码格式,再解码成中文。
.encode(‘latin1’).decode(‘gbk’)
.encode(‘latin1’)等价于.encode(‘l1’)
@staticmethod
def cn_garbled_code(resList):
"""
数据库返回中文乱码问题解决,进来一个list进行处理
"""
target_list = []
target_index = 0
for item in resList:
target_list.insert(target_index,list(item))
target_index+=1
for item in target_list:
for item1 in item:
if type(item1) is str:
try:
if(chardet.detect(item1.encode('l1'))['encoding'] != 'ascii'):
# print(item1.encode('l1').decode("GBK"))
item_index = target_list.index(item)
item1_index = item.index(item1)
target_list[item_index][item1_index] = item1.encode("l1").decode("GBK")
except UnicodeEncodeError:
# print("不用编码")
pass
return target_list
核心代码
try:
if(chardet.detect(item1.encode('l1'))['encoding'] != 'ascii'):
# print(item1.encode('l1').decode("GBK"))
item_index = target_list.index(item)
item1_index = item.index(item1)
target_list[item_index][item1_index] = item1.encode("l1").decode("GBK")
except UnicodeEncodeError:
# print("不用编码")
pass
参考博客:https://blog.csdn.net/qimowei/article/details/113702044