执行增删改操作方法 :db.execSQL(sql); 或者db.insert()、db.delete()、db.update(),并且包括数据表的创建和删除等等也可以通过execSQL实现
代码如下:
//创建表
public boolean createTable(){
SQLiteDatabase db=dbHelper.getWritableDatabase();
String sql="CREATE TABLE IF NOT EXISTS "+TABLE_NAME+"(ID INTEGER PRIMARY KEY,Name VARCHAR,Age INTEGER)";
try{
db.execSQL(sql);
return true;
}catch(SQLException ex){
Log.d(tag, "create table failure");
return false;
}
}
//添加数据
public boolean addData(){
String name=etname.getText().toString();
String age=etage.getText().toString();
SQLiteDatabase db=dbHelper.getWritableDatabase();
String sql="insert into "+TABLE_NAME+"(name,age) values ('"+name+"','"+age+"')";
try{
db.execSQL(sql);
return true;
}catch(SQLException ex){
Log.d(tag, "add data failure");
return false;
}
}
//修改
public boolean updateData(){
SQLiteDatabase db=dbHelper.getWritableDatabase();
String sql="update "+TABLE_NAME+" set age='2' where name like 'cb'";
Object[] bindArgs={"cb"};
try{
db.execSQL(sql, bindArgs);
return true;
}catch(SQLException ex){
Log.d(tag, "update data failure");
return false;
}
}
执行数据查询方法:db.rawQuery(sql, selectionArgs); 或者db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
代码如下:
//查询 public void selectData(){
SQLiteDatabase db=dbHelper.getReadableDatabase();
String[] columns={"name"};
Cursor cursor=db.query(TABLE_NAME, columns, null, null, null, null, null);
String names="";
while(cursor.moveToNext()){
int c=cursor.getColumnIndexOrThrow("Name");
String name=cursor.getString(c);
// =
//String name=cursor.getString(0);//只查询了一列
if(names==""){
names=name;
}else{
names=names+"n"+name;
}
}
tvname.setText(names);
//另外一种查询方法
//String sql="select name from "+TABLE_NAME;
//Curosr cursor=db.rawQuery(sql, null);
}