【发布时间】:2014-12-24 12:49:53
【问题描述】:
我正在尝试使用 Python 在 StringIO 对象中写入数据,然后最终使用 psycopg2 的 copy_from() 函数将此数据加载到 postgres 数据库中。
首先,当我这样做时,copy_from() 抛出了一个错误:错误:用于编码“UTF8”的无效字节序列:0xc92 所以我关注了this question。
我发现我的 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 db 获得)写入 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>)
【问题讨论】:
-
请出示您的代码
-
您使用的是哪个 MySQL 包装器?
-
另外,不要显示“我的一些代码”,而是创建一个自包含的minimal, complete, verifiable example 并在此处发布。
-
我使用 MySQLdb 作为 python 包从 MySQL 中检索数据
-
同时,在您的更新和回复之后,仍然没有 MCVE,并且其他关键信息仅在 cmets 中可见,这意味着任何人搜索都是因为他们想帮助像您这样的人或因为他们有类似的问题不会看到它。
标签: python postgresql python-2.7 encoding utf