使用 cx_Oracle 查询 Oracle DB 时日文字符显示为问号

Japanese characters showing up as question marks on querying Oracle DB, using cx_Oracle

我正在使用 cx_Oracle v7.1.3 和 Python 3.6.4。我当前的 Oracle 数据库有英文、日文和数值。英文和数值检索正常,但日文文本显示为 '???'.

我的第一个想法是这必须对编码做些什么,也许默认的 ASCII 会引发问题,所以我使用 str.encode() 尝试将日文字符串编码为 UTF8,但是徒劳无功。在打印它们时,它们只显示 b'????'

with open('get_table_names.sql', 'r') as file:
  for line in file:
     SQL_QUERY = str(line)

cursor.execute(SQL_QUERY)
# Inner cursor to read inner fields
new_cursor = connection.cursor()
for desc, table_name in cursor:
  # print(cursor.description)
  new_cursor.execute("SELECT * FROM {}".format(table_name.lower()))    

with, open 块只是从文件中读取 SQL 查询。游标执行它并检索所有要查询的 table 的名称,并且 new_cursor 用于读取每个 table.

我们将不胜感激。

在开始之前使用您的字符集设置 NLS_LANG 环境变量 Python,或者(更容易)在连接时使用 encoding,请参阅 https://cx-oracle.readthedocs.io/en/latest/module.html#cx_Oracle.connect

使用类似的东西:

conn = cx_Oracle.connect("user/password@hostname/servicename", encoding="UTF-8", nencoding="UTF-8")

您可能需要不同的编码。

也许首先你可以检查你的os字符集和数据库字符集:

cursor.execute("""select 'DB: ' || value as db_charset from nls_database_parameters where parameter = 'NLS_CHARACTERSET'
union
select distinct 'Client: ' || client_charset from v$session_connect_info where sid = sys_context('USERENV', 'SID')""")
v = c.fetchall()
print(v)

这可能有助于解决您的问题。

import os
os.environ["NLS_LANG"] = ".UTF8"