Tiedien
Tiedien

Reputation: 27

Backup a sqlite3 database

I have a Python project where I use sqlite3 to save data.

I want to do a backup of the database ( I am really worried about datalock, cause my software will be used by like 10 peoples which will have to access to my database to write or read, and without luck, someone will try to access to the database at the bad moment, even if I will increase timeout)

If I do it manually with the Windows cmd, there is no problem.

v:
cd V:\directory\
sqlite3 mydatabase.db"
.backup backup_db.db

I try to do a batch file which will be call every hours by my python software to do it automatically. I applied the same commands in it.

The batch file is launched, but the process stop after the opening of the database. The dot command is not executed.

Where is my mistake?

Upvotes: 2

Views: 5084

Answers (2)

Brian Minton
Brian Minton

Reputation: 3777

The syntax for the sqlite3 executable is sqlite3 [db_file] [command]. So, in your batch file, you should include .backup on the same line.

v:
cd V:\directory\
sqlite3 mydatabase.db ".backup backup_db.db"

Upvotes: 1

Tomalak
Tomalak

Reputation: 338228

Batch files do not work the way you think they do.

You currently think that after the line sqlite3 "mydatabase.db" you are in some kind of "database mode" and all the following lines in the batch file are passed to the sqlite3 process.

That's not the case.

Every line in a batch file is executed after the previous like has finished running.

The line sqlite3 "mydatabase.db" starts the sqlite3 process... and then waits until this process exits. Which never happens unless you do it manually by pressing a key.

And after that cmd.exe will try to execute the command .backup backup_db.db, but since that's not a command cmd.exe understands, it will fail with an error ("'.backup' is not recognized as an internal or external command, operable program or batch file.").

What you really want to do is create a script file and pass it to for SQLite for processing. This can be done by

  • redirecting a file into the sqlite3 process. Assume that create_backup.txt contains the commands to create a backup:

    sqlite3 "mydatabase.db" < create_backup.txt
    
  • piping the file into the sqlite3 process, e.g. using type:

    type create_backup.txt | sqlite3 "mydatabase.db"
    

    alternatively you can use echo to output a command:

    echo .backup backup_db.db | sqlite3 "mydatabase.db"
    

Obviously the echo method is easier for one-liners whereas the input redirect with < or writing out a file with type are easier to for more complex, multi-line operations.

Using the -init parameter of sqlite3.exe is another option you can try. Check the SQLite documentation.

Upvotes: 2

Related Questions