[英]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.