How to Create a Backup of a SQLite Database using Python?
In this article, we will learn How to Create a Backup of an SQLite Database using Python. To Create a Backup of an SQLite Database using Python, the required modules are SQLite3 and IO.
First, let’s create the original database to do that follow the below program:
Original database in memory:
Then we will create a student Table in the original database. We will execute the SQLite syntax to create a table in the cursor object.
cursor_object = conn.cursor()
cursor_object.execute(“CREATE TABLE Table name()”)
Below is the complete program to create a student Table in the original database :
To check if our table is created, we can use the DB Browser for SQLite to view our table. Open ‘originaldatabase.db’ file with the program, and we should see our table:
Creating a backup of Database
We will create a backup of the database. To do that we will call the open() function from the IO module. This function will give the total number of database rows that will be modified, inserted, or deleted since the database connection was opened. Also, we will use iterdump() function. In an SQL text format iterdump() function gives an iterator to dump the database. Which is used to save an in-memory database for later restoration. In the sqlite3 shell, This function provides the same capabilities as the .dump command.
with io.open('backupdatabase.sql', 'w') as p: for line in conn.iterdump(): p.write('%s\n' % line)
By given Syntax backup will be performed successfully and data will be Saved as backupdatabase_dump.sql.
Back up of original database:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course