"SQLite" Python backup Database

Source: Internet
Author: User
Tags sqlite

How to back up the entire database:

#Coding=utf-8ImportSqlite3defTestbaksqlite (): Conn= Sqlite3.connect ("sqlite_db_mine/testdb.db") with open ('TestDB.sql.bak','W') as F: forLineinchconn.iterdump (): Data= line +'\ n'Data= Data.encode ("Utf-8") f.write (data) testbaksqlite ()

If you want to back up one of these tables, there is no good way. Here are some online discussions.

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

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

ImportSqlite3defgettabledump (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'PrintGettabledump (Db_file, Table_to_dump)

Pro: Simplicity and reliability:you don ' t has to re-write any library method, and is more assured that the Code is compatible with the versions of the Sqlite3 module.

Con: You need to load the whole table in memory, which may or may isn't a big deal depending on how big the TA BLE is, and how much memory is available.

SQLite python Backup Database

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.