Vấn đề Unicode với Python 3- Oracle

Đối với Python 3 thì string tự động được sử dụng với Unicode nhưng khi sử dụng Tiếng Việt thao tác xuống Database Oracle hoặc hiển thị dữ liệu Tiếng Việt lên thì bị lỗi.

Để khắc phục điều này khi sử dụng connect tới DB thì cần khai báo encoding và nencoding: cx_Oracle.connect(‘admin’,’admin’,dsn_tns,encoding=”UTF-8″, nencoding=”UTF-8″)

Ví dụ hoàn thiện với việc thêm mới dữ liệu Tiếng Việt:

#!/usr/bin/python

# -*- coding: utf8 -*-
from unicodedata import normalize
import cx_Oracle
cursor, connection = None, None
try:
    dsn_tns = cx_Oracle.makedsn('192.168.177.xxx' , 1522, 'orcl')
    connection = cx_Oracle.connect('admin','admin',dsn_tns,encoding="UTF-8", nencoding="UTF-8")
    cursor = connection.cursor()
    a=u"Lý do"
    b="reasons"
    c="INSERT INTO VN_TEMP_DIC (VN, EN,DAY_TIME,STATUS) VALUES ('%s','%s',sysdate,0)" % (a,b)
    cursor.execute(c)
    cursor.execute("COMMIT")
except cx_Oracle.DatabaseError as e:
    raise e
except Exception as e:
    raise e     
finally:
    if cursor != None:
        cursor.close()
    if connection != None:
        connection.close()


    

Ví dụ hoàn thiện với việc hiển thị dữ liệu tiếng Việt load từ DB:

#!/usr/bin/python
# -*- coding: utf8 -*-

import cx_Oracle
dsn_tns = cx_Oracle.makedsn('xxxxxxxxx' , 1522, 'orcl')
connection = cx_Oracle.Connection('admin','admin',dsn_tns,encoding="UTF-8", nencoding="UTF-8")
cur=connection.cursor()
content = 'however it not depend on column INDPOSTPONEADVANTAGES'
listword=content.split()
listr="";
for re in listword:
    listr=listr+"','"+re
listr=listr
listr=listr[3:]   
print(listr)
query="select a.EN,a.VN from VN_TEMP_DIC a where trim(a.EN) in('%s') order by a.STATUS desc,a.DAY_TIME desc" % (listr)
#print(query)
cur.execute(query)
for result in cur:
    print(result[0]+" - "+result[1])
cur.close()
connection.close