首页 > 数据库技术 > 详细

【sqlite】python备份数据库

时间:2016-10-20 22:01:57      阅读:386      评论:0      收藏:0      [点我收藏+]

备份整个数据库的方法:

# coding=utf-8
import sqlite3

def testBakSqlite():
    conn = sqlite3.connect("sqlite_db_mine/testDB.db")
    with open(testDB.sql.bak,w) as f:
        for line in conn.iterdump():
            data = line + \n
            data = data.encode("utf-8")
            f.write(data)
    
testBakSqlite()

 

 

如果想要备份其中的一个表,没有很好的办法。下面是一些网上的讨论。

http://stackoverflow.com/questions/6677540/how-do-i-dump-a-single-sqlite3-table-in-python

You can copy only the single table in an in memory db:

import sqlite3

def getTableDump(db_file, table_to_dump):
    conn = sqlite3.connect(:memory:)    
    cu = conn.cursor()
    cu.execute("attach database ‘" + db_file + "‘ as attached_db")
    cu.execute("select sql from attached_db.sqlite_master "
               "where type=‘table‘ and name=‘" + table_to_dump + "")
    sql_create_table = cu.fetchone()[0]
    cu.execute(sql_create_table);
    cu.execute("insert into " + table_to_dump +
               " select * from attached_db." + table_to_dump)
    conn.commit()
    cu.execute("detach database attached_db")
    return "\n".join(conn.iterdump())

TABLE_TO_DUMP = table_to_dump
DB_FILE = db_file

print getTableDump(DB_FILE, TABLE_TO_DUMP)

Pro: Simplicity and reliability: you don‘t have to re-write any library method, and you are more assured that the code is compatible with future versions of the sqlite3 module.

Con: You need to load the whole table in memory, which may or may not be a big deal depending on how big the table is, and how much memory is available.

【sqlite】python备份数据库

原文:http://www.cnblogs.com/dplearning/p/5982267.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!