日期:2014-05-16  浏览次数:20426 次

Android---把数据保存到数据库中(二)

把数据放入数据库

通过把ContentValues对象传入instert()方法把数据插入数据库:

// Gets the data repository in write mode 
SQLiteDatabase
db = mDbHelper.getWritableDatabase(); 
 
// Create a new map of values, where column names are the keys 
ContentValues values = new ContentValues(); 
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); 
 
// Insert the new row, returning the primary key value of the new row 
long newRowId; 
newRowId = db.insert( 
         FeedReaderContract.FeedEntry.TABLE_NAME, 
         FeedReaderContract.FeedEntry.COLUMN_NAME_NULLABLE, 
         values);

insert()方法的第一个参数是表名。第二个参数提供了框架中的一个列名,在ContentValues的值是空的时候,框架会向表中插入NULL值(如果这个参数是“null”,那么当没有值时,框架不会向表中插入一行。

 

从数据库中读取数据

要从数据库中读取数据,就要使用query()方法,你需要给这个方法传入选择条件和你想要获取数据的列。查询结果会在Cursor对象中被返回。

SQLiteDatabase db = mDbHelper.getReadableDatabase(); 
 

// Define a projection that specifies which columns from the database 
// you will actually use after this query. 
String[] projection = { 
    FeedReaderContract.FeedEntry._ID, 
    FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE, 
    FeedReaderContract.FeedEntry.COLUMN_NAME_UPDATED, 
    ... 
    }; 
 
// How you want the results sorted in the resulting Cursor 
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 
    se