sqlite详解
1.SQLiteStatement提升多次操作的性能
2.删除表字段:sqlite不支持删除字段,只支持增加字段吗,只能重命名旧表 重建新表 导入数据 然后删除旧表这样
1.查询表中所有数据
select * from 表名
2.查询数据总数
select count(*) as total from 表名
3.where 用法
select * from Person where name = '小红'
4.like用法
查询Person表中name中带有‘小’字的数据
select * from Person where name like '%小%'
5.in的用法
表示某个字段中包含的情况
//age 为22,或者23的情况
select * from Person where age in (22,23)
7.limit与offset共用 分页
offset表示从哪个位置开始查询,可以用来分页查询
//从表中101条数据开始查询返回至少100条数据(如果有100以上的情况)
select * from Person limit 100 offset 101
8.order by 排序
默认为正序 asc
select * from Person order by id asc
倒序desc
select * from Person order by id desc
9.替代符 代替表名
有时表名太长,我们完全可用中间替代符
//下面用t直接代替guangzhou_person表,我们也可用其他字符,注意不要用特殊字符
select * from guangzhou_person t where t.name = '小红'
建表:
CREATE TABLE
IF NOT EXISTS
User(
id Integer primary key,
name varchar not null,
age Integer)
删表:
DROP TABLE IF EXISTS User
SQLiteStatement
private static final String INSERT_SQL = "insert or replace into " + CityItem.TABLE_NAME + "("
+ CityItem.CITYID + " , " + CityItem.CITYNAME + " , " + CityItem.ENGNAME + " , "
+ CityItem.CITYLEVEL + " , " + CityItem.PARENTID + " , " + CityItem.CITYFULLNAME + " , "
+ CityItem.INITIAL + ") values(?, ?, ?, ?, ?, ?, ?)";
public void coverCityList(List<CityItem> list) {
SQLiteStatement stmt = dbHandler.getDB().compileStatement(INSERT_SQL);
dbHandler.beginTransaction();
for (CityItem city : list) {
stmt.bindString(1, city.getCityID());
stmt.bindString(2, city.getCityName());
stmt.bindString(3, city.getEngName());
stmt.bindString(4, city.getCityLevel());
stmt.bindString(5, city.getParentID());
stmt.bindString(6, city.getCityFullName());
stmt.bindString(7, city.getInitial());
stmt.execute();
}
dbHandler.commitTransaction();
dbHandler.endTransaction();
}
}
使用 SQLiteStatement。
普通的insert语句在执行过程过程中,是编译一次sql,再插入数据。
SQLiteStatement采取的方式是预编译一次sql,然后用编译好的语句,和设置的参数执行插入,
无形之中,减少了n-1次sql编译时间。
表的字段操作
SQLite 仅仅支持 ALTER TABLE 语句的一部分功能,我们可以用 ALTER TABLE 语句来更改一个表的名字,也可向表中增加一个字段(列),但是我们不能删除一个已经存在的字段,或者更改一个已经存在的字段的名称、数据类型、限定符等等。
改变表名 - ALTER TABLE 旧表名 RENAME TO 新表名
-
增加一列 - ALTER TABLE 表名 ADD COLUMN 列名 数据类型
而修改一列无法像其他数据库那样直接以“ALTER TABLE 表名 ADD COLUMN 列名 数据类型”的方式来完成,所以要换种思路,具体步骤看下面
-
将表名改为临时表
ALTER TABLE "Student" RENAME TO "_Student_old_20140409";
-
创建新表
CREATE TABLE "Student" ( "Id" INTEGER PRIMARY KEY AUTOINCREMENT, "Name" Text);
-
导入数据
NSERT INTO "Student" ("Id", "Name") SELECT "Id", "Title" FROM "_Student_old_20140409";
-
更新sqlite_sequence
UPDATE "sqlite_sequence" SET seq = 3 WHERE name = 'Student';
由于在Sqlite中使用自增长字段,引擎会自动产生一个sqlite_sequence表,用于记录每个表的自增长字段的已使用的最大值,所以要一起更新下。如果有没有设置自增长,则跳过此步骤。
-
删除临时表(可选)
DROP TABLE _Student_old_20140409;