SQL數據庫SQLite

SQL常用語句

//數組

//寫文件 data string
//NSU
//NSF
//100000000 —> 99

//數據庫 寫文件 —> dict key value –> 哈希算法

//基本單位 表(字段 字段的類型)

//出現一個區分唯一的數據字段 主鍵

//二進制位
//整形 integer
//浮點型 double real
//字符串 varchar() —> text
//bool bool boolean
//二進制數據 blob

//操作數據庫 —> SQL語句

//Student name age
//創建一個表
//create table if not exists 表名 (字段名字1 字段類型 primary key,字段名字2 字段類型 not null,….);

//create table if not exists Student (name text,age integer);

//插入數據
//insert into 表名 (字段1,字段2,…) values (值1,值2,…);

//
//insert into Student (name,age) values (‘zhangsan’,10);

//查詢數據
//查詢所有的字段的值 *
//select 字段名1,字段2,… from 表名 where 條件 order by 字段 desc | asc;多個條件 可以用 and or

//select name from Student;
//select * from Student where name = ‘zhangsan’;
//select * from Student order by age asc;

//修改
//update 表名 set 字段名 = 值 where 條件;
//update Student set age = 1000 where name = ‘zhangsan’;

//刪除
//delete from 表名 where 條件; 不帶條件刪除所有的數據
//delete from Student where name = ‘zhangsan’;

//SQLite

import “FMDatabase.h”

//1.libsqlite3.0.dylib

import “ViewController.h”

@interface ViewController ()

@end

@implementation ViewController

  • (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSString *docPath = [NSString stringWithFormat:@”%@/Documents/stu.db”,NSHomeDirectory()];
    NSLog(@”%@”,docPath);
    //1.必須先創建一個數據庫
    FMDatabase *dataBase = [FMDatabase databaseWithPath:docPath];

    //打開文件
    [dataBase open];

    //2 創建表
    //id 設定爲主鍵 並且值自動增長
    NSString *sqlStr = @”create table if not exists Student (id integer primary key autoincrement,name text,age integer)”;

    [dataBase executeUpdate:sqlStr];

if 0
//插入數據
//? –> %ld sql語句中的佔位符
sqlStr = @”insert into Student (name,age) values (?,?)”;

for (NSInteger i = 0; i < 10; i++) {
    NSString *name = [NSString stringWithFormat:@"qianfeng%ld",i];
    NSInteger age = arc4random() % 100 + 1;

    //executeUpdate 參數 必須都是對象 不能是基本數據類型
    [dataBase executeUpdate:sqlStr,name,[NSNumber numberWithInteger:age]];
}

endif

//查詢數據
sqlStr = @"select * from Student where age < 50";
FMResultSet *set = [dataBase executeQuery:sqlStr];

while ([set next]) {
    NSLog(@"%@",[set stringForColumn:@"name"]);
    NSLog(@"%d",[set intForColumn:@"age"]);
}

//更新數據
sqlStr = @"update Student set age = ? where name = ?";
[dataBase executeUpdate:sqlStr,@100,@"qianfeng0"];

//刪除
sqlStr = @"delete from Student";
[dataBase executeUpdate:sqlStr];

//關閉文件
[dataBase close];


//封裝

//登錄   --->  用戶和密碼   查詢
//註冊   --->  先判斷 用戶 是否存在(查詢數據庫)  不存在  插入數據庫
//修改密碼 --->  用戶

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章