Skip to content

Instantly share code, notes, and snippets.

@Viyu
Created April 2, 2015 06:02
Show Gist options
  • Save Viyu/f0565c46dbcda6140415 to your computer and use it in GitHub Desktop.
Save Viyu/f0565c46dbcda6140415 to your computer and use it in GitHub Desktop.
Key-Value Table
/**
* 专门用来存储key-value的表格,shared preferences的db版
* From db version 1
* @author viyu
*/
public final class KeyValueTable {
/**
* @param key
*/
public static void deleteByKey(String key) {
SQLiteDatabase db = SQLHelper.getInstance().getWritableDatabase();
db.delete(KeyValueEntry.TABLE_NAME, KeyValueEntry.COLUMN_NAME_KEY + "='" + key + "'", null);
db.close();
}
public static void insertKeyValuePair(KeyValueEntry entry) {
SQLiteDatabase db = SQLHelper.getInstance().getWritableDatabase();
ContentValues values = new ContentValues();
//
values.put(KeyValueEntry.COLUMN_NAME_KEY, entry.getKey());
values.put(KeyValueEntry.COLUMN_NAME_VALUE, entry.getValue());
//
db.insert(KeyValueEntry.TABLE_NAME, null, values);
db.close();
}
public static String getValueByKey(String key) {
SQLiteDatabase db = SQLHelper.getInstance().getReadableDatabase();
String[] projection = { KeyValueEntry.COLUMN_NAME_VALUE };
String selection = KeyValueEntry.COLUMN_NAME_KEY + "='" + key + "'";
Cursor cursor = db.query(KeyValueEntry.TABLE_NAME, projection, selection, null, null, null, null);
if (cursor == null || cursor.moveToFirst() == false) {
cursor.close();
db.close();
return null;
}
//
String value = null;
if(cursor.moveToFirst()) {
int valueColumn = cursor.getColumnIndex(KeyValueTable.KeyValueEntry.COLUMN_NAME_VALUE);
value = cursor.getString(valueColumn);
}
cursor.close();
db.close();
return value;
}
public static class KeyValueEntry implements BaseColumns {
/**
* 表名
*/
public static final String TABLE_NAME = "DB_KeyValue";
/**
* key
*/
public static final String COLUMN_NAME_KEY = "key";
/**
* value
*/
public static final String COLUMN_NAME_VALUE = "value";
private String mKey = null;
private String mValue = null;
public KeyValueEntry(String key, String value) {
mKey = key;
mValue = value;
}
public String getKey() {
return mKey;
}
public String getValue() {
return mValue;
}
}
public static final String SQL_CREATE_TABLE = "CREATE TABLE " + KeyValueEntry.TABLE_NAME + " ("
+ KeyValueEntry.COLUMN_NAME_KEY + " TEXT PRIMARY KEY" + SEP_COMMA + KeyValueEntry.COLUMN_NAME_VALUE + TYPE_TEXT
+ " )";
public static final String SQL_DROP_TABLE = "DROP TABLE IF EXISTS " + KeyValueEntry.TABLE_NAME;
public static final String TYPE_TEXT = " TEXT";
public static final String TYPE_INTEGER = " INTEGER";
public static final String SEP_COMMA = ",";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment