【发布时间】:2014-12-25 18:54:06
【问题描述】:
我正在使用 Python 2.7 和 MySQLdb 1.2.3。我尝试了在 stackoverflow 和其他论坛上找到的所有内容来处理我的脚本抛出的编码错误。
我的脚本从源 MySQL DB 中的所有表中读取数据,将它们写入 python StringIO.StringIO 对象,然后将该数据从 StringIO 对象加载到 Postgres 数据库(显然是 UTF-8 编码格式。我发现了这个通过使用 psycopg2 库的 copy_from 命令查看属性--pgadmin 中的数据库定义)。
我发现我的源 MySQL 数据库有一些表采用 latin1_swedish_ci 编码,而另一些表采用 utf_8 编码格式(从 information_schema.tables 中的 TABLE_COLLATION 中找到)。
根据我在互联网上的研究,我在 Python 脚本的顶部编写了所有这些代码。
db_conn = MySQLdb.connect(host=host,user=user,passwd=passwd,db=db, charset="utf8", init_command='SET NAMES UTF8' ,use_unicode=True)
db_conn.set_character_set('utf8')
db_conn_cursor = db_conn.cursor()
db_conn_cursor.execute('SET NAMES utf8;')
db_conn_cursor.execute('SET CHARACTER SET utf8;')
db_conn_cursor.execute('SET character_set_connection=utf8;')
我仍然得到下面这行的UnicodeEncodeError:cell = str(cell).replace("\r", " ").replace("\n", " ").replace("\t", '').replace("\"", "") #Remove unwanted characters from column value,
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 47: ordinal not in range(128)
在写入 StringIO 对象时,我编写了以下代码行来清理源 MySQL 数据库的每个表中的单元格。
cell = str(cell).replace("\r", " ").replace("\n", " ").replace("\t", '').replace("\"", "") #Remove unwanted characters from column value
请帮忙。
【问题讨论】:
标签: python mysql postgresql encoding