Android学习笔记_SQLite的使用
SQLite使用方法
publicclassDatabaseHelperextendsSQLiteOpenHelper{
privatestaticfinalintVERSION=1;
publicDatabaseHelper(Contextcontext,Stringname,CursorFactoryfactory,intversion){
super(context,name,factory,version);
}
publicDatabaseHelper(Contextcontext,Stringname){
this(context,name,VERSION);
}
publicDatabaseHelper(Contextcontext,Stringname,intversion){
this(context,name,null,version);
}
publicvoidonCreate(SQLiteDatabasedb){
db.execSQL("createtableuser(idint,namevarchar(20))");
System.out.println("createaDatabase");
}
publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
System.out.println("updateaDatabase");
}
}
publicclassSQLiteActivityextendsActivity{
classUpdateListenerimplementsOnClickListener{
publicvoidonClick(Viewv){
DatabaseHelperdbHelper=newDatabaseHelper(SQLiteActivity.this,"test_mars_db",2);
SQLiteDatabasedb=dbHelper.getReadableDatabase();
}
}
classInsertListenerimplementsOnClickListener{
publicvoidonClick(Viewv){
ContentValuesvalues=newContentValues();
values.put("id",1);
values.put("name","zhangsan");
DatabaseHelperdbHelper=newDatabaseHelper(SQLiteActivity.this,"test_mars_db");
SQLiteDatabasedb=dbHelper.getWriteableDatabase();
db.insert("user",null,values);
}
}
classUpdateRecordListenerimplementsOnClickListener{
publicvoidonClick(Viewv){
DatabaseHelperdbHelper=newDatabaseHelper(SQLiteActivity.this,"test_mars_db");
SQLiteDatabasedb=dbHelper.getWriteableDatabase();
ContentValuesvalues=newContentValus();
values.put("name","zhangsanfeng");
db.update("user",values,"id=?",newString[]{"1"});
}
}
classQueryListenerimplementsOnClickListener{
publicvoidonClick(){
DatabaseHelperdbHelper=newDatabaseHelper(SQLiteActivity.this,"test_mars_db");
SQLiteDatabasedb=dbHelper.getWriteableDatabase();
Cursorcursor=db.query("user",newString[]{"id","name"},"id=?");
while(cursor.moveToNext()){
Stringname=cursor.getString(cursor.getColumnIndex("name"));
System.out.println("query----->"+name);
}
}
}
}