LitePal的使用(上)--原始的数据操作 增删改查

看了郭神的博客 来总结下我理解的Litepal
没有分析源码的那个能力 就写一下Litepal的基本增删查改吧
数据库里表的对应方式有多种
一对一
A—-1
B—–2
C—–3

一对多
A—-1
A—2
A—3

多对多
A—-1
A—2
A—3
B—1
B—2
B—-3
来说下谷歌官方数据操作的步骤
android.database.sqlite官方api
新建一个实现了SQLiteOpenHelper类的例子
public class FeedReaderDbHelper extends SQLiteOpenHelper {

public FeedReaderDbHelper(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
    db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // This database is only a cache for online data, so its upgrade policy is
    // to simply to discard the data and start over
    db.execSQL(SQL_DELETE_ENTRIES);
    onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    onUpgrade(db, oldVersion, newVersion);
}

}
重写里面的方法
为了访问db 需要实例化这个类
FeedReaderDbHelper mDbHelper=new FeedReaderDbHelper(getcontext());
通过ContentValues对象到insert()方法;
ContentValues values = new ContentValues();
通过values添加数据
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_CONTENT, content);
long newRowId;
newRowId = db.insert(
FeedReaderContract.FeedEntry.TABLE_NAME,
FeedReaderContract.FeedEntry.COLUMN_NAME_NULLABLE,
values);
从db中读取信息
String[] projection = {
FeedReaderContract.FeedEntry._ID,
FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE,
FeedReaderContract.FeedEntry.COLUMN_NAME_UPDATED,

};
String sortOrder= FeedReaderContract.FeedEntry.COLUMN_NAME_UPDATED + ” DESC”;
Cursor c = db.query(
FeedReaderContract.FeedEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don’t group the rows
null, // don’t filter by row groups
sortOrder // The sort order
);
再通过moveToFirst()函数提取cursor的信息
cursor.moveToFirst();
long itemId = cursor.getLong(
cursor.getColumnIndexOrThrow(FeedReaderContract.FeedEntry._ID)
);

删除db中的信息
// Define ‘where’ part of query.
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID + ” LIKE ?”;
// Specify arguments in placeholder order.
String[] selelectionArgs = { String.valueOf(rowId) };
// Issue SQL statement.
db.delete(table_name, mySelection, selectionArgs);
更新数据
SQLiteDatabase db = mDbHelper.getReadableDatabase();

// New value for one column
ContentValues values = new ContentValues();
values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, title);

// Which row to update, based on the ID
String selection = FeedReaderContract.FeedEntry.COLUMN_NAME_ENTRY_ID + ” LIKE ?”;
String[] selectionArgs = { String.valueOf(rowId) };

int count = db.update(
FeedReaderDbHelper.FeedEntry.TABLE_NAME,
values,
selection,
selectionArgs);

你可能感兴趣的:(数据库,android)