【问题标题】:How can I copy data from a SQL_ASCII to a UTF8 postgresql db using SQLAlchemy?如何使用 SQLAlchemy 将数据从 SQL_ASCII 复制到 UTF8 postgresql db?
【发布时间】: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


    【解决方案1】:

    原来解决办法是把连接client_encoding设置为'latin1'

    我使用 PoolListener 完成了这项工作,如下所示:

    class EncodingListener(PoolListener):
    
        def connect(self, dbapi_con, con_record):
            with closing(dbapi_con.cursor()) as cur:
                cur.execute('show client_encoding')
                encoding = cur.fetchone()[0]
    
            if encoding.upper() == 'UTF8':
                return
    
            dbapi_con.set_client_encoding('latin1')
    

    【讨论】:

      【解决方案2】:

      既然 UTF-8 向后兼容 UTF-8,为什么要使用 SQL_ASCII 而不是 UTF8

      我认为您的编码问题可能更多地与latin1 或类似编码有关。不是ASCIIUTF8

      【讨论】:

      • 你这是什么意思?数据库已经在 SQL_ASCII 中,我对此没有太多发言权。
      • @Chris R:我的意思是,为源数据库指定SQL_ASCIIUTF8 并不重要,因为UTF8 向后兼容ASCII
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-20
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多