How to backup sqlite database?

时光总嘲笑我的痴心妄想 提交于 2019-11-27 10:43:15
Googie

The sqlite3 command line tool features the .backup dot command.

You can connect to your database with:

sqlite3 my_database.sq3

and run the backup dot command with:

.backup backup_file.sq3

Instead of the interactive connection to the database, you can also do the backup and close the connection afterwards with

sqlite3 my_database.sq3 ".backup 'backup_file.sq3'"

Either way the result is a copy named backup_file.sq3 of the database my_database.sq3.

It's different from regularly file copying, because it takes care of any users currently working on the database. There are proper locks set on the database, so the backup is done exclusively.

.backup is the best way.

sqlite3 my_database .backup my_database.back

you can also try .dump command , it gives you the ability to dump the entire database or tables into a text file. If TABLE specified, only dump tables matching LIKE pattern TABLE.

sqlite3 my_database .dump > my_database.back

A good way to make an archival copy using dump and store, Reconstruct the database at a later time.

sqlite3 my_database .dump | gzip -c > my_database.dump.gz
zcat my_database.dump.gz | sqlite3 my_database

Also check this question Do the SQLite3 .backup and .dump commands lock the database?

try {
    final String inFileName = "/data/data/your app package/databases/db";
    File dbFile = new File(inFileName);
    FileInputStream fis = new FileInputStream(dbFile);
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/CALC/Backup";
    File dir = new File(path);
    if (!dir.exists()) dir.mkdirs();
    String outFileName = path + "/filename"; // output file name
    // Open the empty db as the output stream
    OutputStream output = new FileOutputStream(outFileName);

    // Transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = fis.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
    Toast.makeText(getActivity(), "Backup Successfully", 2).show();
    // Close the streams
    output.flush();
    output.close();
    fis.close();
} 
catch (Exception e) {
    e.printStackTrace();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!