SQLite 初學

weixin_34116110發表於2016-06-27
pragma mark - 01 SQLite資料劃分
integer:整型值
real:浮點值
text:文字字串
blob:二進位制資料(比如檔案)
pragma mark - 02 建立資料表格
  • DDL:資料定義語句
//建立表
格式
#create table if not exists 表名 (欄位名1 欄位型別1, 欄位名2 欄位型別2, …) ;
#t_class:表名(要以t_開頭)
#primary key autoincrement:主鍵,要自動增長
create table if not exists t_class (id integer primary key autoincrement,name text);
//刪除表
drop table if exists t_class;

pragma mark - 03 運算元據庫表格(增刪改查)
  • DML:資料操作語句
//插入表格
格式
#insert into 表名 (欄位1, 欄位2, …) values (欄位1的值, 欄位2的值, …) ;
示例
insert into t_student (name, age) values (‘mj’, 10) ;
注意
資料庫中的字串內容應該用單引號 ’ 括住

//更新
格式
update 表名 set 欄位1 = 欄位1的值, 欄位2 = 欄位2的值, … ; 
示例
update t_student set name = ‘jack’, age = 20 ; 
注意
上面的示例會將t_student表中所有記錄的name都改為jack,age都改為20

//刪除
格式
delete from 表名 ;
示例
delete from t_student ;
注意
上面的示例會將t_student表中所有記錄都刪掉

pragma mark - 04 條件語句
如果只想更新或者刪除某些固定的記錄,那就必須在DML語句後加上一些條件

條件語句的常見格式
where 欄位 = 某個值 ;   // 不能用兩個 =
where 欄位 is 某個值 ;   // is 相當於 = 
where 欄位 != 某個值 ; 
where 欄位 is not 某個值 ;   // is not 相當於 != 
where 欄位 > 某個值 ; 
where 欄位1 = 某個值 and 欄位2 > 某個值 ;  // and相當於C語言中的 &&
where 欄位1 = 某個值 or 欄位2 = 某個值 ;  //  or 相當於C語言中的 ||

示例
將t_student表中年齡大於10 並且 姓名不等於jack的記錄,年齡都改為 5
update t_student set age = 5 where age > 10 and name != ‘jack’ ;

刪除t_student表中年齡小於等於10 或者 年齡大於30的記錄
delete from t_student where age <= 10 or age > 30 ;

猜猜下面語句的作用
update t_student set score = age where name = ‘jack’ ;
將t_student表中名字等於jack的記錄,score欄位的值 都改為 age欄位的值

pragma mark - 05 查詢表
  • DQL:語句
格式
select 欄位1, 欄位2, … from 表名 ;
select * from 表名;   //  查詢所有的欄位
示例
select name, age from t_student ;
select * from t_student ;
select * from t_student where age > 10 ;  //  條件查詢