1. 建表
CREATE TABLE 表名 (列名1 类型,列名2 类型)
例:
create table if not exists person(persionid integer primary key autoincrement, name varchar(20));
db.execSQL("CREATE TABLE person (personid integer primary key autoincrement, name varchar(20))");
2.修改表
ALTER TABLE 表名 ADD 列名 类型 NULL
例:
alter table person add phone varchar(20);
db.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL ");
3. 插入信息
insert into 表名 (列名1,列名2 )values (值1,值2);
例:
insert into person(name,phone) values('peter','123');
db.execSQL("insert into person (name,phone) values (?,?)", new Object[] { "peter", "123"});
ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
// 如果 contentvalues为空
db.insert("person", null, values); // 组拼sql语句完成的添加的操作
4. 删除信息
delete from 表名 where 条件
例:
delete from person where name = "peter";
db.execSQL("delete from person where name =?", new Object[] { "peter"});
db.delete("person", "name=?", new String[] { name });
5.更新信息
update person set name='p',phone='456' where name='peter';
db.execSQL("update person set name=? , phone=? where name=?", new Object[] { newname, newphone, name });
ContentValues values = new ContentValues();
values.put("name", newname);
values.put(“phone”, newphone);
db.update("person", values, "name=?", new String[] { name });
6.查询信息
select 列名 from 表名 where 条件
例:
select * from person where name="peter";
db.rawQuery("select * from person where name=?", new String[] { name });
Cursor cursor = db.query("person", null, "name=?",
new String[] { name }, null, null, null);
7.查询个数
select count(column) from 表名
select count(*) from person;
db.rawQuery("select count(*) from person", null);
if(cursor.moveToNext()) {
int index = cursor.getColumnIndex("columnName");
int count = cursor.getInt(index);
}
8.删除全部数据
db.execSQL("delete from "+ TABLE_NAME);
db.delete(TABLE_NAME, null, null);
db.delete(TABLE_NAME, "1", null);
9.cursor的使用情景:
a.需要requery()操作的情况;
b.需要监听数据库变化时。
registerContentObserver(ContentObserver observer);