android数据库操作

packagecom.tcl.kang;

importandroid.content.ContentValues;

importandroid.content.Context;

importandroid.database.Cursor;

importandroid.database.sqlite.SQLiteDatabase;

importandroid.database.sqlite.SQLiteOpenHelper;

publicclassDatabaseHelperextendsSQLiteOpenHelper

{

privatestaticfinalStringname="mydatabase";

privatestaticfinalStringTABLE_name="tb_test";

privatestaticfinalintVERSION=1;

privateStringTABLE_NUM="_num";

privateStringTABLE_DATA="_data";

publicDatabaseHelper(Contextcontext)

{

super(context,NAME,null,VERSION);

//TODOAuto-generatedconstructorstub

}

@Override

publicvoidonCreate(SQLiteDatabasedb)

{

//TODOAuto-generatedmethodstub

Stringsql="CREATETABLE"

+TABLE_NAME

+"(_idINTEGERPRIMARYKEYAUTOINCREMENT,_numtext,_datatext)";

db.execSQL(sql);//需要异常捕获

}

@Override

publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion)

{

//TODOAuto-generatedmethodstub

Stringsql="droptable"+"tb_test";

db.execSQL(sql);

onCreate(db);

}

/**

*添加数据

*/

publiclonginsert(Stringnum,Stringdata)

{

SQLiteDatabasedb=getWritableDatabase();//获取可写SQLiteDatabase对象

//ContentValues类似map,存入的是键值对

ContentValuescontentValues=newContentValues();

contentValues.put(TABLE_NUM,num);

contentValues.put(TABLE_DATA,data);

returndb.insert(TABLE_NAME,null,contentValues);

}

/**

*/**删除记录

*

*@param_id

*/

publicvoiddelete(Stringid)

{

SQLiteDatabasedb=getWritableDatabase();

db.delete(TABLE_NAME,"_id=?",newString[]{id});

}

/**

*更新记录的,跟插入的很像

*/

publicvoidupdate(String_id,Stringnum,Stringdata){

SQLiteDatabasedb=getWritableDatabase();

ContentValuescontentValues=newContentValues();

contentValues.put(TABLE_NUM,num);

contentValues.put("TABLE_DATA",data);

db.update(TABLE_NAME,contentValues,

"_id=?",

newString[]{_id});

}

/**

*查询所有数据

*@returnCursor

*/

publicCursorselect(){

SQLiteDatabasedb=getReadableDatabase();

returndb.query(

TABLE_NAME,

newString[]{"_id",TABLE_NUM,TABLE_DATA},

null,

null,null,null,"_iddesc");//desc降序排列,asc升序排列

}

}

相关推荐