21

可能重复:
Android 备份/恢复:如何备份内部数据库?

我正在开发一个包含 SQL lite db 的应用程序。我需要让用户能够备份数据库并再次恢复它。我怎样才能做到这一点?示例代码?

如果我的用户保存了数据库,然后将应用程序升级到新的数据库版本代码,恢复工作是否可行?我该怎么做?

4

2 回答 2

42

在“/data/data/'your.app.package'/databases/”文件夹中,您有一个 .db 文件,它是您的数据库。您可以复制该文件,保存它,然后将其放回原处。

关于如何将数据库备份到外部存储的一个示例:

    final String inFileName = "/data/data/<your.app.package>/databases/foo.db";
    File dbFile = new File(inFileName);
    FileInputStream fis = new FileInputStream(dbFile);

    String outFileName = Environment.getExternalStorageDirectory()+"/database_copy.db";

    // 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);
    }

    // Close the streams
    output.flush();
    output.close();
    fis.close();
于 2012-11-22T01:39:35.360 回答
3

你能澄清一下“备份”是什么意思吗?SQLite 没有特定的备份方法;您必须从数据库中读取行并以某种方式保存它们。许多开发人员使用 XML 来执行此操作。

如果用户保存了数据库,然后您转移到新的数据库版本代码,您必须决定如何进行恢复。同样,必须完成读取备份并将其放回数据库的工作;SQLite 和 Android 都不会为您执行此操作。

包 android.app.backup 包含用于使用 Android 备份代理的类,但它们实现了一个通用框架。您可以为要备份的每个文件或数据库实施具体细节。

于 2012-11-21T22:06:50.940 回答