在 Python 上从 Oracle 数据库中提取数据。面临多字节字符的问题

问题描述 投票:0回答:1

我正在尝试从 Oracle 数据库获取数据,只是将其保存在 csv 文件中。当我尝试使用默认编码执行此操作时,我收到错误:'utf-8'编解码器无法解码位置 14 中的字节 0xd1:无效的连续字节。。数据库的字符集是 AL32UTF8,国家的字符集是 AL16UTF8。有些客户已经把记录放在西班牙语上,所以有些字符ñ被替换为and ?。 我尝试将编码更改为 ISO-8859-1,这适用于前 2 个查询,但对于其他查询,我遇到“部分多字节字符”错误。我还用查询检查数据,还有其他吗?替换品。 这是我的代码(请忽略凭据和查询,我只是输入了一些随机值)

`

os.environ['NLS_LANG'] = 'AMERICAN_AMERICA.AL32UTF8' connection = None cursor = None dir = './csv_files/' queries = { 'file_name.csv': "SELECT * table", 'file_name.csv': "SELECT * FROM table", } if not os.path.exists(dir): os.makedirs(dir) try: dsn_tns = cx_Oracle.makedsn('171.11.1.111', '1521', sid='ñññ') connection = cx_Oracle.connect(user, password, dsn=dsn_tns, encoding='ISO-8859-1') cursor = connection.cursor() for file_name, query in queries.items(): try: cursor.execute(query) rows = cursor.fetchall() columns = [col[0] for col in cursor.description] dataFrame = pd.DataFrame(rows, columns=columns) file_path = os.path.join(dir, file_name) dataFrame.to_csv(file_path, index=False, encoding='utf-16', errors= 'replace') except Exception as e: print(f"Error in query for {file_name}: {e}") continue except Exception as e: print(f"Error in connection: {e}") finally: if cursor is not None and connection is not None: cursor.close()

`

如何在不从数据库中删除冲突数据的情况下处理此问题?

我尝试过更改编码,但都不起作用。

python oracle character-encoding export-to-csv multibyte-characters
1个回答
0
投票
https://python-oracledb.readthedocs.io/en/latest/user_guide/sql_execution.html#fetching-raw-data

我必须将 cx_Oracle 代码迁移到 oracble db。

© www.soinside.com 2019 - 2024. All rights reserved.