[英]How can I dump my sqlite3 database to SQL in UTF8 with django?
有没有人知道如何解决下一个问题?
现在我正在使用此代码:
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)
我收到这个错误:
异常类型:
Unicode编码错误异常值:
'ascii' 编解码器无法对位置 112 中的字符 u'\\xe9' 进行编码:序号不在范围内 (128)
无法编码/解码的字符串是:(Arivé, PAK
感谢您查看这个!
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'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.