确定的SQLite的大小,内存数据库 [英] Determine the size of SQLite in-memory database

查看:115
本文介绍了确定的SQLite的大小,内存数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大的数据库,我记得在Android上。有很多行和行的尺寸是稍微可变的。我怎样才能在运行时确定的内存数据库的大小?

I have a large database I keep in memory on Android. There are a lot of rows and the size of the row is somewhat variable. How can I determine the size of the in-memory database at run-time?

推荐答案

确定,这里就是我想出了解决方案。它不是pretty,但它的作品。

OK, here is the solution I came up with. It isn't pretty, but it works.

Android的 SQLiteDatabase 类包括设置一个最大数据库大小的方法,<一个href=\"https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#setMaximumSize(long)\"相对=nofollow> setMaximumSize(长的numBytes)。最大尺寸不能设定的电流大小的下方。因此该解决方案是设置的最大尺寸的页文件的大小和看到该方法返回什么尺寸。下面是在方法我 SQLiteOpenHelper 类:

Android's SQLiteDatabase class includes a method that sets a maximum database size, setMaximumSize(long numBytes). The maximum size cannot be set below the current size. So the solution is to set the maximum size to the page file size and see what size the method returns. Here's the method in my SQLiteOpenHelper class:

public synchronized int getDatabaseUsage() {
    SQLiteDatabase db = getWritableDatabase();
    long pageSize = db.getPageSize();
    long savedMaximumSize = db.getMaximumSize();
    long appliedSize = db.setMaximumSize(pageSize);
    int percentageUsed = (int) ((appliedSize * 100) / savedMaximumSize);
    db.setMaximumSize(savedMaximumSize);
    Log.v(LOG_TAG, "Percentage database space used: " + percentageUsed);
    return percentageUsed;
}

我设置的最大尺寸是设备的大内存类的:

private static final long BYTES_IN_A_MEGABYTE = 1048576;

/**
 * Maximum size of the database in bytes
 */
private final long mMaxSize;

public SQLHelper(Context context) {
    super(context, null, null, DATABASE_VERSION);
    mMaxSize = BYTES_IN_A_MEGABYTE * Helper.getLargeMemoryClass(context);
}

public void onCreate(SQLiteDatabase db) {
    <database creation code>
    db.setMaximumSize(mMaxSize);
}

然后我每次批量插入前检查数据库的使用。如果使用率高于50,我从表中删除旧行并运行真空命令来恢复空间。

Then I just check the database usage before every bulk insert. If the usage is above 50, I delete old rows from the table and run the vacuum command to recover space.

/**
 * Rebuilds the entire database.
 * <p/>
 * This reclaims empty space left behind after deletions.
 */
public void vacuum(SQLiteDatabase db) {
    db.execSQL("VACUUM");
}

这篇关于确定的SQLite的大小,内存数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆