您的位置:首页 > 移动开发 > IOS开发

iOS开发之FMDB

2015-12-14 22:06 513 查看
使用数据库之前当然要先在网上下载FMDB的库,然后添加到自己的工程里面去。没有的请点击下面的来下载

fmdb

一般来说,我们把一个应用的数据库建在当前程序的沙盒里,所以,我们要先取得沙盒的路径

在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];

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: