python讀取us7ascii字符集Oracle數據庫中文亂碼問題的解決方案


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")

 

如果有驗證過的更簡潔的可行方案,請賜教!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM