我正在尝试使用 Python 在 StringIO 对象中写入数据,然后最终使用 psycopg2 的 copy_from() 函数将此数据加载到 postgres 数据库中。
首先,当我这样做时,copy_from()抛出错误:错误:编码“UTF8”的字节序列无效:0xc92所以我遵循这个问题.
我发现我的 Postgres 数据库有 UTF8 编码。
我正在写入数据的文件/StringIO 对象显示其编码如下:
setgid 非 ISO 扩展 ASCII 英文文本,行很长,带有 CRLF 行终止符
我尝试将写入中间文件/StringIO 对象的每个字符串编码为 UTF8 格式。为此,对每个字符串使用 .encode(encoding='UTF-8',errors='strict')) 。
这是我现在得到的错误:
UnicodeDecodeError:“ascii”编解码器无法解码位置 47 中的字节 0x92:序号不在范围内(128)
这是什么意思?我如何解决它?
编辑:
我正在使用Python 2.7
我的一些代码:
我从 MySQL 数据库读取数据,该数据库按照 MySQL Workbench 以 UTF-8 编码的数据。
这是几行代码,用于将我的数据(从 MySQL 数据库获取)写入 StringIO 对象:
# Populate the table_data variable with rows delimited by \n and columns delimited by \t
row_num=0
for row in cursor.fetchall() :
# Separate rows in a table by new line delimiter
if(row_num!=0):
table_data.write("\n")
col_num=0
for cell in row:
# Separate cells in a row by tab delimiter
if(col_num!=0):
table_data.write("\t")
table_data.write(cell.encode(encoding='UTF-8',errors='strict'))
col_num = col_num+1
row_num = row_num+1
这是从我的 StringIO 对象 table_data 写入 Postgres 数据库的代码:
cursor = db_connection.cursor()
cursor.copy_from(table_data, <postgres_table_name>)