标签:
转自:http://blog.it985.com/3677.html
使用数据库之前当然要先在网上下载FMDB的库,然后添加到自己的工程里面去。没有的请点击下面的来下载
fmdb
在FrameWork里添加“libsqulite3.0.dylib”,不然库托进去后会引起大量报错。
一般来说,我们把一个应用的数据库建在当前程序的沙盒里,所以,我们要先取得沙盒的路径
在AppDelegate.m中
|
1
2
3
4
5
6
|
- (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中
|
1
2
3
4
5
|
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate]; myDelegate.dbPath = [self dataFilePath]; return YES;} |
路径准备好之后,下一步就是在本地创建数据库和表
数据库的语句基本上都是很容易从字面上看懂的
在AppDelegate.m中
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
- (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文件使用库的话就可以像下面这样
如果要在表中插入一组新的数据
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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的姓名和地址)
|
1
2
|
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”是检测是否出错的标志位,如果不想用的话可以不用的。还有,想往数据库加入整型数据的话可能会报错,建议把整型转换成字符串再添加,像下面这样。
|
1
2
3
|
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 本地数据库的创建和几个基本使用方法
标签:
原文地址:http://www.cnblogs.com/feiyu-mdm/p/5568495.html