繁体   English   中英

检查数据库SQLite Android的完整性

[英]Check integrity of Database SQLite Android

我的服务器中有一个SQLite数据库文件,我的Android App会不时检查是否有新的SQLite数据库文件。 如果为true,则应用程序将下载文件并替换旧数据库。

问题是,如果我不手动在“ Android设置”中清理应用程序,有时新的数据库文件会损坏并且应用程序开始崩溃,并且永远无法恢复。

我的问题是,有没有办法在下载后检查SQLite数据库的完整性?

这是我的代码,用于从服务器上下载新数据库,并将此代码放置在AssyncTask中:

protected Boolean doInBackground(String... Url) {
        try {
                URL url = null;
                if(Url[0].equals("")){
                    mSyncDate = mConnectionManager.getSyncDate();
                    url = new URL(Constants.HF_SERVER_DATABASE+"db_fxbus_"+convertDateToFormatYYYYMMDD(mSyncDate.getServerDate())+".sqlite");
                }else{
                    url = new URL(Url[0]);
                }
                URLConnection connection = url.openConnection();
                connection.connect();
                // this will be useful so that you can show a typical 0-100% progress bar
                int fileLength = connection.getContentLength();

                mDB.getReadableDatabase();
                // download the file
                InputStream input = new BufferedInputStream(url.openStream());
                Log.i(TAG, "Path:"+mContext.getDatabasePath("HorariosDoFunchal").getAbsolutePath());
                OutputStream output = new FileOutputStream(mContext.getDatabasePath("HorariosDoFunchal").getAbsolutePath());
                startWriting = true;
                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                    //Log.i(TAG, "Executing ...");
                }
                //Log.i(TAG, "Finish ...");

                output.flush();
                output.close();
                input.close();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
            return false;
        }
        return true;
    }

调查:

pragma integrity_check;

它将扫描数据库并检查其是否有错误以及其他情况。 在此链接中可以找到更多信息(和更多命令):

http://www.sqlite.org/pragma.html

还可以查看isDatabaseIntegrityOk()的文档。

您可以尝试使用PRAGMA integrity_check (或Android等效的isDatabaseIntegrityOk() ),但这只会检查数据库结构是否存在错误,并且只能在可以证明结构错误的地方检测到错误。

为了能够检测所有错误(特别是在您自己的数据中),您需要为整个数据库文件计算一个校验和。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM