在android应用程序中使用db.execSQL(“sql”,bindArgs)操作增删改查语句;
1、创建表结构
public void create(View v){
db.execSQL("create table person (id integer primary key autoincrement,name varchar(20))", new Object[]{});
Toast.makeText(this, "创建表结构成功", 0).show();
}
2、插入
public void insert(View v){
db.execSQL("insert into person (name)values(?)", new String[]{"lisi"});
Toast.makeText(this, "插入数据成功", 0).show();
}
3、查询:db.rawQuery,cursor类似于一个指针,当cursor指向一条记录时,就把当前记录的数据封装到cursor中,直接从cursor取数据
public void query(View v){
Cursor cursor = db.rawQuery("select * from person",null);
//移动游标,返回值为true表示没有移动到数据集的最后(空),如果为false已经数据集的最后(没有数据了)
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String name = cursor.getString(1);
System.out.println("id="+id+"; name="+name);
}
Toast.makeText(this, "查询数据成功", 0).show();
}
4、更新
public void update(View v){
db.execSQL("update person set name='wangwu' where id=?", new Object[]{1});
Toast.makeText(this, "更新数据成功", 0).show();
}
4、删除
public void delete(View v){
db.execSQL("delete from person where id=?", new Object[]{1});
Toast.makeText(this, "删除数据成功", 0).show();
}
数据库的另外一种增删改查方法:
使用google提供的另外一种方式操作数据库表:
1、插入数据
public void insert(View v){
//db.execSQL("insert into person (name)values(?)", new String[]{"lisi"});
ContentValues values = new ContentValues();
Random r = new Random();
values.put("name", "zhangsan"+r.nextInt(100));
long rowId = db.insert("person", null, values);
System.out.println("rowId="+rowId);
Toast.makeText(this, "插入数据成功", 0).show();
}
2、查询数据
public void query(View v){
/**
* table 表名
* columns 查询的列
* selection 查询条件”id=1”
* selectionArgs 查询条件的值
* String groupBy
* String having
* String orderBy
*
*/
Cursor cursor = db.query(“person”, new String[]{“id”,”name” }, null, null, null, null, null);
while(cursor.moveToNext()){
int id = cursor.getInt(0);
String name = cursor.getString(1);
System.out.println("id="+id+"; name="+name);
}
Toast.makeText(this, "查询数据成功", 0).show();
}
public void update(View v){
// db.execSQL("update person set name='wangwu' where id=?", new Object[]{1});
//用来封装要修改的列名和值
ContentValues values = new ContentValues();
values.put("name", "wangwu");
db.update("person", values, "id=?", new String[]{"1"});
Toast.makeText(this, "更新数据成功", 0).show();
}
public void delete(View v){
// db.execSQL(“delete from person where id=?”, new Object[]{1});
db.delete(“person”, “id=?”, new String[]{“2”});
Toast.makeText(this, “删除数据成功”, 0).show();
}