【发布时间】:2010-12-14 22:51:00
【问题描述】:
我正在写一个db数据迁移工具,使用SQLAlchemy的表达式语言作为基本工具。
我的源数据库可能是 UTF8,也可能是 SQL_ASCII。我的目标数据库将始终使用 UTF8。
我在 SQLAlchemy 0.6.6 中使用 psycopg2 驱动程序
我的一般迁移过程如下所示:
for t in target_tables:
log.info("Migrating data from %s", t.fullname)
source = self.source_md.tables[self.source_schema + "." + t.name]
for row in source.select().execute():
with sql_logging(logging.INFO):
conn.execute(t.insert(), row)
如果我没有在引擎上设置任何与编码相关的内容,我会在迭代 select() 结果时得到这个:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128)
如果我在引擎上设置use_native_unicode=True, encoding='utf-8',我会在尝试插入新行时得到这个:
sqlalchemy.exc.DataError: (DataError) invalid byte sequence for encoding "UTF8": 0xeb6d20
HINT: This error can also happen if the byte sequence does not match the encoding expected by the server, which is controlled by "client_encoding".
'INSERT INTO project_ghtests_survey000005.employees (first_name, employee_id) VALUES (%(first_name)s, %(employee_id)s)' {'first_name': 'Art\xebm', 'employee_id': '1234'}
更新详情
为了让查询更快一点,这里是正在运行的软件堆栈:
- source_db 编码:
SQL_ASCII - target_db 编码:
UTF8 - python 2.7
- sqlalchemy 0.6.6
- psycopg2 2.2.2
- PostgreSQL 8.2 服务器
【问题讨论】:
标签: python postgresql unicode character-encoding sqlalchemy