SQLite 数据库操作

前端之家收集整理的这篇文章主要介绍了SQLite 数据库操作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
1.创建合同类(contract class)---是一个常量的容器,定义表、列、URIs的名字。

public finalclass FeedReaderContract{ // To prevent someone from accidentally instantiating the contract class,// give it an empty constructor.FeedReaderContract(){}/* Inner class that defines the table contents */staticabstractFeedEntryimplementsBaseColumnsString TABLE_NAME ="entry"; COLUMN_NAME_ENTRY_ID "entryid" COLUMN_NAME_TITLE "title" COLUMN_NAME_SUBTITLE "subtitle"...}}
在合同类中为每张表创建内部类并列举其列。通过实现BaseColumns接口,该内部类会继承一个主键字段"_ID"。它不是必须的,但可以帮你的数据库与Android框架和谐的工作。

2.构造创建表和删除表的语句

private TEXT_TYPE " TEXT" COMMA_SEP "," sql_CREATE_ENTRIES "CREATE TABLE "+FeedEntry.TABLE_NAME " ("_ID " INTEGER PRIMARY KEY,"COLUMN_NAME_ENTRY_ID COLUMN_NAME_TITLE // Any other options for the CREATE command" )" sql_DELETE_ENTRIES "DROP TABLE IF EXISTS "TABLE_NAME;
3.创建 SQLiteOpenHelper 的子类,重写onCreate(),onUpgrade(),onOpen()等回调函数

FeedReaderDbHelperextendssqliteOpenHelper// If you change the database schema,you must increment the database version.int DATABASE_VERSION 1 DATABASE_NAME "FeedReader.db"FeedReaderDbHelper(Context context)super(context,0)"> DATABASE_NAMEnull DATABASE_VERSION);void onCreatesqliteDatabase dbexecsqlsql_CREATE_ENTRIES onUpgrade oldVersion newVersion// This database is only a cache for online data,so its upgrade policy is// to simply to discard the data and start oversql_DELETE_ENTRIESdb onDowngrade}
访问数据库前,先实例化 SQLiteOpenHelper子类:

 mDbHelper newgetContext());
4.向数据库中插入数据

// Gets the data repository in write mode db  mDbHelpergetWritableDatabase();// Create a new map of values,where column names are the keysContentValues values ContentValues valuesputCOLUMN_NAME_ENTRY_ID idCOLUMN_NAME_TITLE titleCOLUMN_NAME_CONTENT content// Insert the new row,returning the primary key value of the new rowlong newRowId newRowId insertCOLUMN_NAME_NULLABLE);
第二个参数提供当ContentValues是空的情况,框架(framework )可以插入NULL的列的名称。当你设置为null的时候,当 ContentValues没有任何值时框架不会插入数据。

5.查询数据库中的数据

getReadableDatabase// Define a projection that specifies which columns from the database// you will actually use after this query.String[] projection _IDCOLUMN_NAME_UPDATED};// How you want the results sorted in the resulting Cursor sortOrder COLUMN_NAME_UPDATED " DESC"Cursor c query// The table to query projection// The columns to return selection// The columns for the WHERE clause selectionArgs// The values for the WHERE clause// don't group the rows// don't filter by row groups sortOrder // The sort order);
查询结果返回一个Cursor(游标),调用Cursor的方法moveToFirst()移动游标到第一个查询出来的行,获得各个列的值。

cursormoveToFirst itemId  cursorgetLonggetColumnIndexOrThrow);
6.删除数据库中的数据。

// Define 'where' part of query. selection " LIKE ?"// Specify arguments in placeholder order. selectionArgs valueOfrowId// Issue sql statement.deletetable_name);
7.更新数据库中的数据。

// New value for one column// Which row to update,based on the ID count update.);

如果看本文头昏脑胀的话,只好say sorry ,提供一篇很好的文章更容易理解,链接如下:

猜你在找的Sqlite相关文章