目前推荐哪种SQLite设计模式?

时间:2015-12-01 21:20:32

标签: android database sqlite

我正在考虑为我的应用程序实现数据库的单例设计模式,而不是经历制作和销毁数据库实例的昂贵操作。

然而,不久前我读到Android和SQLite有几个选项(但我不记得是什么,我找不到链接)所以我想知道,这些数据库建议使用哪些设计模式,它们的优缺点是什么?

谢谢, 利安

1 个答案:

答案 0 :(得分:0)

我使用这个方法。我使用这些单例类SQLiteHelper,SelectionBuilder。

public class SQLiteHelper extends SQLiteOpenHelper {

public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "test.db";

public static final String PRIMARY_KEY = " PRIMARY KEY";
public static final String TYPE_TEXT = " TEXT";
public static final String TYPE_INTEGER = " INTEGER";
public static final String TYPE_REAL = " REAL";
public static final String COMMA_SEP = ",";

public SQLiteHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(Category.SQL_CREATE_TABLE);
    db.execSQL(Article.SQL_CREATE_TABLE);
    db.execSQL(IntroImage.SQL_CREATE_TABLE);
    db.execSQL(Asset.SQL_CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL(Category.SQL_DROP_TABLE);
    db.execSQL(Article.SQL_DROP_TABLE);
    db.execSQL(IntroImage.SQL_DROP_TABLE);
    db.execSQL(Asset.SQL_DROP_TABLE);
}

}

SQLiteOpenHelper是数据库创建和升级的单例。 SelectionBuilder就像它的名字所说的那样是建立选择条款的助手。

public class SelectionBuilder {
private static final String TAG = SelectionBuilder.class.getSimpleName();

private String mTable = null;
private Map<String, String> mProjectionMap = Maps.newHashMap();
private StringBuilder mSelection = new StringBuilder();
private ArrayList<String> mSelectionArgs = Lists.newArrayList();

/**
 * Reset any internal state, allowing this builder to be recycled.
 */
public SelectionBuilder reset() {
    mTable = null;
    mSelection.setLength(0);
    mSelectionArgs.clear();
    return this;
}

/**
 * Append the given selection clause to the internal state. Each clause is
 * surrounded with parenthesis and combined using {@code AND}.
 */
public SelectionBuilder where(String selection, String... selectionArgs) {
    if (TextUtils.isEmpty(selection)) {
        if (selectionArgs != null && selectionArgs.length > 0) {
            throw new IllegalArgumentException(
                    "Valid selection required when including arguments=");
        }

        // Shortcut when clause is empty
        return this;
    }

    if (mSelection.length() > 0) {
        mSelection.append(" AND ");
    }

    mSelection.append("(").append(selection).append(")");
    if (selectionArgs != null) {
        Collections.addAll(mSelectionArgs, selectionArgs);
    }

    return this;
}

public SelectionBuilder table(String table) {
    mTable = table;
    return this;
}

private void assertTable() {
    if (mTable == null) {
        throw new IllegalStateException("Table not specified");
    }
}

public SelectionBuilder mapToTable(String column, String table) {
    mProjectionMap.put(column, table + "." + column);
    return this;
}

public SelectionBuilder map(String fromColumn, String toClause) {
    mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn);
    return this;
}

/**
 * Return selection string for current internal state.
 *
 * @see #getSelectionArgs()
 */
public String getSelection() {
    return mSelection.toString();
}

/**
 * Return selection arguments for current internal state.
 *
 * @see #getSelection()
 */
public String[] getSelectionArgs() {
    return mSelectionArgs.toArray(new String[mSelectionArgs.size()]);
}

private void mapColumns(String[] columns) {
    for (int i = 0; i < columns.length; i++) {
        final String target = mProjectionMap.get(columns[i]);
        if (target != null) {
            columns[i] = target;
        }
    }
}

@Override
public String toString() {
    return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection()
            + ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]";
}

/**
 * Execute query using the current internal state as {@code WHERE} clause.
 */
public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) {
    return query(db, columns, null, null, orderBy, null);
}

/**
 * Execute query using the current internal state as {@code WHERE} clause.
 */
public Cursor query(SQLiteDatabase db, String[] columns, String groupBy,
                    String having, String orderBy, String limit) {
    assertTable();
    if (columns != null) mapColumns(columns);
    Log.v(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this);
    return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having,
            orderBy, limit);
}

/**
 * Execute distinct query using the current internal state as {@code WHERE} clause.
 */
public Cursor queryDistinct(SQLiteDatabase db, String[] columns, String orderBy) {
    return queryDistinct(db, columns, null, null, orderBy, null);
}
/**
 * Execute distinct query using the current internal state as {@code WHERE} clause.
 */
public Cursor queryDistinct(SQLiteDatabase db, String[] columns, String groupBy,
                    String having, String orderBy, String limit) {
    assertTable();
    if (columns != null) mapColumns(columns);
    Log.v(TAG, "queryDistinct(columns=" + Arrays.toString(columns) + ") " + this);
    return db.query(true, mTable, columns, getSelection(), getSelectionArgs(), groupBy, having,
            orderBy, limit);
}

/**
 * Execute update using the current internal state as {@code WHERE} clause.
 */
public int update(SQLiteDatabase db, ContentValues values) {
    assertTable();
    Log.v(TAG, "update() " + this);
    return db.update(mTable, values, getSelection(), getSelectionArgs());
}

/**
 * Execute delete using the current internal state as {@code WHERE} clause.
 */
public int delete(SQLiteDatabase db) {
    assertTable();
    Log.v(TAG, "delete() " + this);
    return db.delete(mTable, getSelection(), getSelectionArgs());
}
}

因此,您可以将这两个帮助器与ContentProvider结合使用,以用于您创建的模型以及使用这些帮助程序定义查询,插入,更新和删除方法的位置。另外,对我来说,最好的方法是将Google Sync Framework与Loaders一起使用。

http://developer.android.com/training/sync-adapters/index.html