需求作用:
如果需要保存大量的結構較為復雜的數據時候, 使用數據庫, 例如交規考試項目
常用的數據庫:
(1)Microsoft SQL Server 2000/2008, 中小企業使用較多
(2)Oracle 比較復雜, 大企業使用較多
(3)MySQL數據庫, 網站使用較多
(4)sqlite: 本地數據庫, 訪問數據足夠快, 直接訪問文件
足夠簡單, 功能相對其他數據庫軟件不是特別齊全, 足夠用了
足夠小, 系統不超過1M, 適合在移動端上使用
實例: 使用數據存儲存儲一個班上學生的信息
學號sid 用戶名username 密碼passWord 成績score
1501 zhangsan 123 100
1502 lilei 321 90
1503 wangwu 222 80
(1)創建數據庫
打開MesaSQlite后如果選擇Cancel,這就是需要你手動創建一個屬于你的數據庫,
選擇File-->New Database ,彈出對話框Save 填寫保存的文件名和位置,
(2)創建數據表
(3)設計數據表(添加多個字段/列)
(4)數據庫常用操作
增,刪,改,查
SQL( Structure Query Language), 結構化查詢語言, 作用就是操作數據庫(創建表, 數據增刪改查)
(1)創建數據表
create table if not exists StudentInfo(sid integer, username varchar(20), password varchar(20),score varchar(20))
(2)插入數據
insert into StudentInfo(sid,username,password,score) values(1503,'wangwu','222','80')
(3)查詢數據
<1>查詢表格中的所有數據
select * from StudentInfo;
<2>查詢指定的字段
例:查詢所有名字username
select username from StudentInfo
<3>根據指定的條件進行查詢
例:查找username為zhangsan的所有信息
select * from StudentInfo where username='zhangsan'
<4>根據多個條件進行查詢
例:查找username為zhangsan,并且password為123的所有信息
select * from StudentInfo where username='zhangsan' and password='123'
<5>查詢后按需要排序
例:根據age升序排序
降序排列
select * from StudentInfo order by score
升序排列
select * from StudentInfo order by score desc
<6>獲取,查詢數據的行數或個數
select count(*) from StudentInfo
(4)修改數據
update StudentInfo set score='100' where username='zhangsan';
(5)刪除數據
delete from StudentInfo where sid='1503'
導入文件,
添加二進制庫 libsqlite3.dylib,
包含頭文件#import "FMDatabase.h"
注意:說明一下iOS的安全機制————沙盒機制
//沙盒機制-(void)SandBox{ //IOS安全機制 - 沙盒 //(1)每個應用內容度放在一個沙盒目錄下面 //(2)每個應用只能修改自己沙盒目錄下得文件,其他應用文件無法修改 //(3)默認文件Documents,Library,tmp //開發:自己創建的文件放在Documents下面 //確定文件位置 //當前應用文件夾 :NSHomeDirectory() NSLog(@"%@",[[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSHomeDirectory() error:nil]); NSLog(@"home == %@",NSHomeDirectory());}
a.創建數據庫
-(void)creatAndInitFMDBDatabase{ //設置路徑 NSString *path = [NSString stringWithFormat:@"%@/Documents/stuInfo.sqlite",NSHomeDirectory()]; //創建數據庫(如果不存在則創建打開,如果存在則直接打開) _database = [[FMDatabase alloc]initWithPath:path]; if (!_database.open) { NSLog(@"失敗"); return; } NSLog(@"成功");}
b.創建數據表
-(void)createTable{ //executeQuery用來執行select語句 //其他語句使用executeUpdate // _database executeQuery:<#(NSString *), ...#> NSString *sql = @"create table if not exists StudentInfo(sid integer,username varchar(20),password varchar(20),score varchar(20))"; BOOL b = [_database executeUpdate:sql]; NSLog(@"creatTable = %d",b);}
c.插入數據
-(void)insertData{ int sid = 1501; NSString *username = @"zhangsan"; NSString *password = @"123"; NSString *score = @"100"; NSString *sql = @"insert into StudentInfo(sid,username,password,score) values(?,?,?,?)"; BOOL b = [_database executeUpdate:sql,[NSString stringWithFormat:@"%d",sid],username,password,score]; NSLog(@"insertData = %d",b);}
d.查詢數據
-(void)queryData{ NSString *sql = @"select * from StudentInfo"; FMResultSet *resultSet = [_database executeQuery:sql]; while ([resultSet next]) { NSLog(@"sid = %@, username = %@, password = %@, score = %@",[resultSet stringForColumn:@"sid"],[resultSet stringForColumn:@"username"],[resultSet stringForColumn:@"password"],[resultSet stringForColumn:@"score"]); }}
e.修改和刪除
//參照數據的插入和查詢
導入文件,
添加二進制庫 libsqlite3.dylib,
包含頭文件#import "FMDatabase.h"
a.創建一個DatabaseManager的單例(繼承NSObject),里面添加兩個方法并實現
//獲取單例對象+(id)sharedInstance;//獲取第一級目錄-(NSArray *)firstLevels;
#import "DatabaseManager.h"#import "FMDatabase.h"@interface DatabaseManager (){ FMDatabase *_database;}@end@implementation DatabaseManager//獲取單例對象+(id)sharedInstance{ static DatabaseManager *dc = nil; if (dc == nil) { dc = [[[self class]alloc]init]; } return dc;}//重寫初始化的方法-(id)init{ if (self = [super init]) { [self openDatabase]; } return self;}//打開數據庫-(void)openDatabase{ NSString *path = [[NSBundle mainBundle]pathForResource:@"data.sqlite" ofType:nil]; _database = [[FMDatabase alloc]initWithPath:path]; if (!_database.open) { NSLog(@"打開失敗"); }}//獲取第一級目錄-(NSArray *)firstLevels{ NSString *sql = @"select *from firstlevel"; FMResultSet *resultSet = [_database executeQuery:sql]; NSMutableArray *marr = [[NSMutableArray alloc]init]; while ([resultSet next]) { FirstLevelModel *model = [[FirstLevelModel alloc]init]; model.pid = [resultSet stringForColumn:@"pid"]; model.pname = [resultSet stringForColumn:@"pname"]; model.pcount = [resultSet stringForColumn:@"pcount"]; [marr addObject:model]; } return marr;}
b.實現
c.創建模型model(FirstLevelModel,繼承NSObject)
#import <Foundation/Foundation.h>@interface FirstLevelModel : NSObject@PRoperty (copy,nonatomic) NSString *pid;@property (copy,nonatomic) NSString *pname;@property (copy,nonatomic) NSString *pcount;@end
導入單例DatabaseManager的頭文件
#import "ViewController.h"#import "DatabaseManager.h"@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>{ UITableView *_tableView ; NSMutableArray *_dataArray; }@end@implementation ViewController- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //初始化_dataArray _dataArray = [[NSMutableArray alloc]init]; //獲取單例 DatabaseManager *manager = [DatabaseManager sharedInstance]; //通過遍歷單例創建Model for (FirstLevelModel *model in manager.firstLevels) { NSLog(@"name = %@",model.pname); //把遍歷后的數據加入到_dataArray中 [_dataArray addObject:model]; } NSLog(@"%d",manager.firstLevels.count); [self creatTableView]; }//創建tableView-(void)creatTableView{ _tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain]; _tableView.delegate = self; _tableView.dataSource = self; //返回cell的高度 _tableView.rowHeight = 50; [self.view addSubview:_tableView ]; //給_dataArray的數據賦值 _dataArray = [[NSMutableArray alloc]initWithArray: [[DatabaseManager sharedInstance] firstLevels]]; }-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ NSLog(@"%d",[[[DatabaseManager sharedInstance] firstLevels] count]); return [[[DatabaseManager sharedInstance] firstLevels] count];}-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{ static NSString *inde = @"cellId"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:inde]; if (cell == nil) { cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:inde]; } //創建model獲取數據并給cell賦值 FirstLevelModel *model = _dataArray[indexPath.row]; cell.textLabel.text = model.pname; return cell;}//是否可以編輯-(BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{ return YES;}
新聞熱點
疑難解答