標籤:
iOS開發之用代碼實現資料庫FMDB的操作1.簡介
需求作用: 如果需要儲存大量的結構較為複雜的資料時候, 使用資料庫, 例如交規考試項目
常用的資料庫:
(1)Microsoft SQL Server 2000/2008, 中小企業使用較多
(2)Oracle 比較複雜, 大企業使用較多
(3)Mysql資料庫, 網站使用較多
(4)sqlite: 本機資料庫, 訪問資料足夠快, 直接存取檔案
足夠簡單, 功能相對其他資料庫軟體不是特別齊全, 足夠用了
足夠小, 系統不超過1M, 適合在移動端上使用
2.FMDB操作資料庫
(1)配置
匯入檔案,
添加二進位庫 libsqlite3.dylib,
包含標頭檔#import "FMDatabase.h"
3.資料庫在項目中使用-單例設計模式
- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //(1)建立資料庫 [self creatAndInitDatabase]; //(2)建立資料表 [self createTable]; //(3)插入資料 [self insertdata]; //(4)查詢資料 [self queryData]; //(5)修改和刪除資料 //參考:插入資料}-(void)queryData{ //顯示所有人的資訊 NSString *sql = @"select * from StudentInfo"; //FMResultSet 表示查詢後結果集 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"]); } }-(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(@"b = %d",b);}-(void)createTable{ NSString *sql=@"create table if not exists StudentInfo(sid integer,username varchar(20),password varchar(20),score varchar(20))"; //executeQuery 用來執行select語句 BOOL b=[_database executeUpdate:sql]; NSLog(@"b=%d",b);}-(void)creatAndInitDatabase{ //ios安全機制 - 沙箱 //(1). 每個應用內容都放在一個沙箱目錄下面 //(2). 每個應用只能修改沙箱目錄下得檔案,其他應用檔案無法修改 //(3). 預設資料夾 Documents,Library,tmp //開發: 自己建立的檔案放在Documents下面 //確定檔案位置 //當前檔案夾: NSHomeDirectory()// NSLog(@"home = %@",NSHomeDirectory());// NSLog(@"%@",[[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSHomeDirectory() error:nil]); //設定路徑 NSString *path = [NSString stringWithFormat:@"%@/Documents/stuInfo.sqlite",NSHomeDirectory()]; //建立資料庫(如果不存在則建立開啟,如果存在則直接開啟) _database = [[FMDatabase alloc] initWithPath:path]; if(![_database open]) { NSLog(@"開啟失敗"); return; } NSLog(@"開啟成功"); }
4.顯示結果
iOS開發之用代碼實現資料庫FMDB的操作