android之sqlite数据库初级

packagecom.example.testsqlite;

importandroid.os.Bundle;

importandroid.app.Activity;

importandroid.content.ContentValues;

importandroid.content.Context;

importandroid.database.Cursor;

importandroid.database.sqlite.SQLiteDatabase;

importandroid.util.Log;

importandroid.view.Menu;

importandroid.widget.Toast;

publicclassMainActivityextendsActivity{

@Override

protectedvoidonCreate(BundlesavedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

//打开或创建test.db数据库

SQLiteDatabasedb=openOrCreateDatabase("test.db",Context.MODE_PRIVATE,null);

db.execSQL("DROPTABLEIFEXISTSperson");

//创建person表

db.execSQL("CREATETABLEperson(_idINTEGERPRIMARYKEYAUTOINCREMENT,nameVARCHAR,ageSMALLINT)");

Personperson=newPerson();

person.name="john";

person.age=30;

//插入数据

db.execSQL("INSERTINTOpersonVALUES(NULL,?,?)",newObject[]{person.name,person.age});

person.name="david";

person.age=33;

//ContentValues以键值对的形式存放数据

ContentValuescv=newContentValues();

cv.put("name",person.name);

cv.put("age",person.age);

//插入ContentValues中的数据

db.insert("person",null,cv);

cv=newContentValues();

cv.put("age",35);

//更新数据

db.update("person",cv,"name=?",newString[]{"john"});

Cursorc=db.rawQuery("SELECT*FROMpersonWHEREage>=?",newString[]{"33"});

while(c.moveToNext()){

int_id=c.getInt(c.getColumnIndex("_id"));

Stringname=c.getString(c.getColumnIndex("name"));

intage=c.getInt(c.getColumnIndex("age"));

Toast.makeText(this,"_id=>"+_id+",name=>"+name+",age=>"+age,Toast.LENGTH_SHORT);

Log.i("db","_id=>"+_id+",name=>"+name+",age=>"+age);

}

c.close();

//删除数据

db.delete("person","age<?",newString[]{"35"});

//关闭当前数据库

db.close();

//删除test.db数据库

//deleteDatabase("test.db");

}

@Override

publicbooleanonCreateOptionsMenu(Menumenu){

//Inflatethemenu;thisaddsitemstotheactionbarifitispresent.

getMenuInflater().inflate(R.menu.main,menu);

returntrue;

}

}

相关推荐