3

有没有人知道如何解决下一个问题?

现在我正在使用这段代码:

def databasedump(request):
    # Convert file existing_db.db to SQL dump file dump.sql
    con = sqlite3.connect('database.sqlite')
    with open('dump.sql', 'w') as f:  
        for line in con.iterdump():
            f.write('%s\n' % line)

我得到这个错误:

异常类型:
UnicodeEncodeError

异常值:
'ascii' 编解码器无法对位置 112 中的字符 u'\xe9' 进行编码:序数不在范围内(128)

无法编码/解码的字符串是:(Arivé,PAK

感谢您查看这个!

4

1 回答 1

3

sqlite3转储代码中有一个错误,在 Python 错误跟踪器中被跟踪为问题 15019 。

您可以通过编辑sqlite3/dump.py文件并在顶部添加以下行来解决此问题:

from __future__ import unicode_literals

通过运行以下命令找到该文件:

python -c 'import sqlite3.dump; print sqlite3.dump.__file__.rstrip("c")'

您必须调整行编写代码以编码现在将从.iterdump()方法返回的 unicode 值:

with open('dump.sql', 'w') as f:  
    for line in con.iterdump():
        f.write('%s\n' % line.encode('utf8'))

如果您对编辑 Python 标准库源文件感到不舒服,请改用以下(固定和缩短的)函数:

def iterdump(connection):
    cu = connection.cursor()
    yield(u'BEGIN TRANSACTION;')

    q = """
        SELECT "name", "type", "sql"
        FROM "sqlite_master"
            WHERE "sql" NOT NULL AND
            "type" == 'table'
        """
    schema_res = cu.execute(q)
    for table_name, type, sql in sorted(schema_res.fetchall()):
        if table_name == 'sqlite_sequence':
            yield(u'DELETE FROM "sqlite_sequence";')
        elif table_name == 'sqlite_stat1':
            yield(u'ANALYZE "sqlite_master";')
        elif table_name.startswith('sqlite_'):
            continue
        else:
            yield(u'{0};'.format(sql))

        table_name_ident = table_name.replace('"', '""')
        res = cu.execute('PRAGMA table_info("{0}")'.format(table_name_ident))
        column_names = [str(table_info[1]) for table_info in res.fetchall()]
        q = """SELECT 'INSERT INTO "{0}" VALUES({1})' FROM "{0}";""".format(
            table_name_ident,
            ",".join("""'||quote("{0}")||'""".format(col.replace('"', '""')) for col in column_names))
        query_res = cu.execute(q)
        for row in query_res:
            yield(u"{0};".format(row[0]))

    q = """
        SELECT "name", "type", "sql"
        FROM "sqlite_master"
            WHERE "sql" NOT NULL AND
            "type" IN ('index', 'trigger', 'view')
        """
    schema_res = cu.execute(q)
    for name, type, sql in schema_res.fetchall():
        yield(u'{0};'.format(sql))

    yield(u'COMMIT;')

像这样使用上面的:

con = sqlite3.connect('database.sqlite')
with open('dump.sql', 'w') as f:  
    for iterdump(con):
        f.write('%s\n' % line.encode('utf8'))
于 2012-11-15T09:43:33.357 回答