SQLite(三)
//插入数据
btn3=(Button)findViewById(R.id.btn3);
btn3.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// 建立数据对象
ContentValues values=new ContentValues();
values.put("id", 2);
values.put("name", "guoxu");
SqlHelper db=new SqlHelper(SqLiteDemoActivity.this, "myhome.db");
// 获得可写的表
SQLiteDatabase sqlitedb=db.getWritableDatabase();
// 插入数据
sqlitedb.insert("user", null, values);
// 关闭数据库
db.close();
System.out.println("data is insert");
}
});
//更新数据
btn4=(Button)findViewById(R.id.btn4);
btn4.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
ContentValues values=new ContentValues();
values.put("name", "郭旭");
SqlHelper db=new SqlHelper(SqLiteDemoActivity.this, "myhome.db");
SQLiteDatabase sqlitedb=db.getWritableDatabase();
sqlitedb.update("user", values, "id=?", new String[]{"1"});
System.out.println("data is update");
db.close();
}
});
//删除数据
btn5=(Button)findViewById(R.id.btn5);
btn5.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
SqlHelper db=new SqlHelper(SqLiteDemoActivity.this, "myhome.db");
SQLiteDatabase sqlitedb=db.getWritableDatabase();
sqlitedb.delete("user", "id=?", new String[]{"2"});
System.out.println("data is update");
db.close();
}
});
//查询数据
btn6=(Button)findViewById(R.id.btn6);
btn6.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
SqlHelper db=new SqlHelper(SqLiteDemoActivity.this, "myhome.db");
SQLiteDatabase sqlitedb=db.getReadableDatabase();
Cursor cursor=sqlitedb.query("user", new String[]{"id","name"},
null, null, null, null, "id desc");
StringBuffer str=new StringBuffer();
while(cursor.moveToNext()){
int id=cursor.getInt(cursor.getColumnIndex("id"));
String name=cursor.getString(cursor.getColumnIndex("name"));
str.append("id="+id);
str.append("<br>name="+name+"<br>");
}
datatxt=(TextView)findViewById(R.id.datatxt);
datatxt.setText(Html.fromHtml(str.toString()));
}
});
}
}