Oracle业务数据库使用的字符集为us7ascii,python执行sql取得结果中的中文为乱码,不管怎么encode、decode编码解码,仍然没有解决。网上类似案例不多,尝试了几种方案,最后参照stackoverflow上的一例https://stackoverflow.com/questions/21336211/how-to-read-national-characters-127-from-us7ascii-oracle-using-python-cx-orac,形成了一个比较绕的解决方案,记录下来。
import pandas as pd import matplotlib.pyplot as plt from sqlalchemy import create_engine import chardet import binascii #import os #os.environ['NLS_LANG'] = 'AMERICAN_AMERICA.US7ASCII' #db = cx_Oracle.connect('usr/pwd@host/orcl') #curs = db.cursor() sql = 'select rawtohex(utl_raw.cast_to_raw(name)) as name from index where patient_id = \'s1\' ' #sql = 'select name from index where patient_id = \'s1\' ' engine = create_engine('oracle://'usr/pwd@host/orcl') df = pd.read_sql_query(sql,engine) tmp = binascii.unhexlify(df['name'][0]) cn = tmp.decode('GBK') print(cn)
方法是在SQL中利用rawtohex的utl_raw.cast_to_raw进行字符转换,然后对查询结果使用decode('GBK').
utl_raw.cast_to_raw可作为一种数据库字符集访问解决思路。
附:
java访问字符集为us7ascii的Oracle数据库中文乱码的解决方案:
str = new String(str.getBytes("GBK"),"iso-8859-1")
如果有验证过的更简洁的可行方案,请赐教!