sqlite詳解
1.SQLiteStatement提升多次操作的性能
2.刪除表字段:sqlite不支持刪除字段,只支持增加字段嗎,只能重命名舊表 重建新表 導入數(shù)據(jù) 然后刪除舊表這樣
1.查詢表中所有數(shù)據(jù)
select * from 表名
2.查詢數(shù)據(jù)總數(shù)
select count(*) as total from 表名
3.where 用法
select * from Person where name = '小紅'
4.like用法
查詢Person表中name中帶有‘小’字的數(shù)據(jù)
select * from Person where name like '%小%'
5.in的用法
表示某個字段中包含的情況
//age 為22,或者23的情況
select * from Person where age in (22,23)
7.limit與offset共用 分頁
offset表示從哪個位置開始查詢惊窖,可以用來分頁查詢
//從表中101條數(shù)據(jù)開始查詢返回至少100條數(shù)據(jù)(如果有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語句在執(zhí)行過程過程中握联,是編譯一次sql桦沉,再插入數(shù)據(jù)。
SQLiteStatement采取的方式是預編譯一次sql拴疤,然后用編譯好的語句,和設置的參數(shù)執(zhí)行插入,
無形之中独泞,減少了n-1次sql編譯時間呐矾。
表的字段操作
SQLite 僅僅支持 ALTER TABLE 語句的一部分功能,我們可以用 ALTER TABLE 語句來更改一個表的名字懦砂,也可向表中增加一個字段(列)蜒犯,但是我們不能刪除一個已經存在的字段,或者更改一個已經存在的字段的名稱荞膘、數(shù)據(jù)類型罚随、限定符等等。
改變表名 - ALTER TABLE 舊表名 RENAME TO 新表名
-
增加一列 - ALTER TABLE 表名 ADD COLUMN 列名 數(shù)據(jù)類型
而修改一列無法像其他數(shù)據(jù)庫那樣直接以“ALTER TABLE 表名 ADD COLUMN 列名 數(shù)據(jù)類型”的方式來完成羽资,所以要換種思路淘菩,具體步驟看下面
-
將表名改為臨時表
ALTER TABLE "Student" RENAME TO "_Student_old_20140409";
-
創(chuàng)建新表
CREATE TABLE "Student" ( "Id" INTEGER PRIMARY KEY AUTOINCREMENT, "Name" Text);
-
導入數(shù)據(jù)
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;