SQLite將數(shù)據(jù)劃分為以下一種存儲類型:
integer:整型
real:浮點型
text:文本字符串
blob:二進制數(shù)據(jù)(比如文件)
建表:
create table t_student(id integer, name text, age integer, score real);
create table if not exists t_student(id integer, name text, age integer, score real);
刪表:
drop table t_student;
drop table t_student if exists;
插入數(shù)據(jù):
insert into t_student (name, age) values (‘zhangsan’, 22);
注意:字符串應該用單引號
更新數(shù)據(jù):
將t_student這張表中所有的name改為jack,age改為20:
update t_student set name=‘jack’,age=20;
將name為jack的score改為99
update t_student set score=99 where name=‘jack’;
刪除表中數(shù)據(jù):
刪除表中所有數(shù)據(jù):
delete from t_student;
刪除name為tom的這條數(shù)據(jù)
delete from t_student where name=‘tom’;
條件語句格式:
“where 字段 = 某個值”
“where 字段 is 某個值” // “is”相當于”=“
“where 字段 != 某個值“
“where 字段 is not 某個值” // “is not”相當于”!=“
“where 字段 > 某個值”
“where 字段1 = 某個值 and 字段2 > 某個值”
“where 字段1 = 某個值 or 字段2 = 某個值”
查詢:
select * from t_student;// 查詢所有字段
select name, age from t_student;// 查詢某些字段
select * from t_student where age > 10;// 條件查詢
起別名:
select name myname ,age myage from t_student;
//給name起個叫做myname的別名,給age起個叫做myage的別名
select s.name, s.age from t_student s;
// 給t_student表起個別名叫做s,利用s來引用表中的字段
計算記錄的數(shù)量:
// 共有多少個學生
select count(age) from t_student;
// score>=60的學生有多少
select count(*) from t_student where score >= 60;
排序:
select * from t_student order by age asc;// 升序
select * from t_student order by age desc;// 降序
select * from t_student order by age asc, score desc;
// 先按age升序排,如果age相等按score降序排
limit:
select * from t_student limit 4, 8;
// 跳過前面4條數(shù)據(jù),然后取8條數(shù)據(jù)
select * from t_student limit 7;
// 這句相當于:select * from t_student limit 0, 7;
limit常用來做分頁查詢,比如每頁固定顯示5條數(shù)據(jù),那么應該這樣取數(shù)據(jù):
第一頁:limit 0, 5
第二頁:limit 5, 5
第三頁:limit 10, 5
…
第n頁:limit 5*(n-1), 5
簡單約束:
建表時可以給特定的字段設置一些約束條件,常見的約束有:
not null:規(guī)定字段的值不能為空
unique:規(guī)定字段的值必須唯一
default:指定字段的默認值
create table t_student(id integer, name text not null unique, age integer not null default 1);
// name字段不能為空,并且唯一
// age字段不能為空,默認值為1
主鍵約束:
主鍵:用來唯一標識某一條記錄
主鍵應當是對用戶沒有意義的
永遠也不要更新主鍵
主鍵不應包含動態(tài)變化的數(shù)據(jù)
主鍵應當由計算機自動生成
create table t_student(id integer primary key, name text, age integer);
// 如果某個字段是主鍵,該字段默認包含了not null 和 unique兩個約束
create table t_student(id integer primary key autoincrement, name text, age integer);
// 自動增長的主鍵