標籤:
轉自:http://blog.it985.com/3677.html
使用資料庫之前當然要先在網上下載FMDB的庫,然後添加到自己的工程裡面去。沒有的請點擊下面的來下載
fmdb
在FrameWork裡添加“libsqulite3.0.dylib”,不然庫托進去後會引起大量報錯。
一般來說,我們把一個應用的資料庫建在當前程式的沙箱裡,所以,我們要先取得沙箱的路徑
在AppDelegate.m中
| 123456 |
- (NSString *) dataFilePath//應用程式的沙箱路徑{ NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *document = [path objectAtIndex:0]; return [document stringByAppendingPathComponent:@"StudentData.sqlite"];} |
如果其他檔案中也要使用資料庫的話,取得沙箱路徑後把路徑設為全域變數
在AppDelegate.h中
| 1 |
@property (strong, nonatomic) NSString *dbPath; |
在AppDelegate.m中
| 12345 |
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate]; myDelegate.dbPath = [self dataFilePath]; return YES;} |
路徑準備好之後,下一步就是在本地建立資料庫和表
資料庫的語句基本上都是很容易從字面上看懂的
在AppDelegate.m中
| 123456789101112131415161718 |
- (void)createTable{ AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate]; NSFileManager *fileManager = [NSFileManager defaultManager]; FMDatabase *db = [FMDatabase databaseWithPath:myDelegate.dbPath]; if (![fileManager fileExistsAtPath:myDelegate.dbPath]) { NSLog(@"還未建立資料庫,現在正在建立資料庫"); if ([db open]) { [db executeUpdate:@"create table if not exists StudentList (name text, address text, id text)"]; [db close]; }else{ NSLog(@"database open error"); } } NSLog(@"FMDatabase:---------%@",db);} |
這樣,我們就建立了一個名為“db”的資料庫,和名為“StudentList”的表。
值得注意的是,建立資料庫之後如果要使用的話一定要在使用之前進行[db open],使用結束後[db close]。這是千萬不能忘的。
之後我們要在其他.m檔案使用庫的話就可以像下面這樣
如果要在表中插入一組新的資料
| 1234567891011121314 |
AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];FMDatabase *db = [FMDatabase databaseWithPath:myDelegate.dbPath];[db open];NSString *name = @"蘋果";NSString *address = @"安徽";int i = 1;NSString *id = [NSString stringWithFormat:@"%d",i];res = [db executeUpdate:@"INSERT INTO StudentList (name, address, id) VALUES (?, ?, ?)", name, address, id];if (res == NO) { NSLog(@"資料插入失敗"); }else{ NSLog(@"資料插入成功"); }[db close]; |
修改資料庫(把id為1的地址和姓名修改掉)
| 1 |
res = [db executeUpdate:@"UPDATE StudentList SET name = ?, address = ? WHERE id = ?",@"橘子",@"蕪湖",1]; |
查詢資料庫(查詢id為1的姓名和地址)
| 12 |
NSString *nameOut = [db stringForQuery:@"SELECT name FROM StudentList WHERE id = ?",1];NSString *addressOut= [db stringForQuery:@"SELECT address FROM StudentList WHERE id = ?",1]; |
刪除資料庫(刪除id為1的資料)
| 1 |
res = [db executeUpdate:@"DELETE FROM StudentList WHERE id = ?",1]; |
說明一下上面的”res”是檢測是否出錯的標誌位,如果不想用的話可以不用的。還有,想往資料庫加入整型資料的話可能會報錯,建議把整型轉換成字串再添加,像下面這樣。
| 123 |
int i = 1;NSString *id = [NSString stringWithFormat:@"%d",i];res = [db executeUpdate:@"INSERT INTO StudentList (name, address, id) VALUES (?, ?, ?)", name, address, id]; |
本文永久地址:http://blog.it985.com/3677.html
本文出自 IT985部落格 ,轉載時請註明出處及相應連結。
iOS FMDatabase 本機資料庫的建立和幾個基本使用方法