18 - (void)viewDidLoad
19 {
20 [super viewDidLoad];
21
22 //1.获得数据库文件的路径
23 NSString *doc=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
24 NSString *fileName=[doc stringByAppendingPathComponent:@"person.sqlite"];
25
26 //2.获得数据库队列
27 FMDatabaseQueue *queue=[FMDatabaseQueue databaseQueueWithPath:fileName];
28 // FMDatabase *db=[FMDatabase databaseWithPath:fileName];
29
30 //3.打开数据库
31 [queue inDatabase:^(FMDatabase *db) {
32 BOOL result=[db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_person (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"];
33 if (result) {
34 NSLog(@"创表成功");
35 }else
36 {
37 NSLog(@"创表失败");
38 }
39 }];
40 self.queue=queue;
42 }
44 -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
45 {
46 //插入数据
47 // [self.queue inDatabase:^(FMDatabase *db) {
48 // [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @22];
49 // }];
50
51 //查询数据
52 [self.queue inDatabase:^(FMDatabase *db) {
53 // 1.执行查询语句
54 FMResultSet *resultSet = [db executeQuery:@"SELECT * FROM t_person"];
55
56 // 2.遍历结果
57 while ([resultSet next]) {
58 int ID = [resultSet intForColumn:@"id"];
59 NSString *name = [resultSet stringForColumn:@"name"];
60 int age = [resultSet intForColumn:@"age"];
61 NSLog(@"%d %@ %d", ID, name, age);
62 }
63 }];
64
65 }
66
67 @end
事务,没有事务的话会出现问题。
举例:银行的例子
张三和李四账户都有1000块钱,如果张三要转账给李四,需要执行两条SQL语句,考虑到安全性,要求这两条鱼具要么全部执行成功,要不全部执行失败。
事务:把多条语句放到同一个事务中,要么全部成功,要不全部失败(如果中途出现问题,那么会自动回滚)。事务的执行具有原子性。
事务代码处理:
把多条语句添加到一个事务中去执行:
1 //插入数据
2 [self.queue inDatabase:^(FMDatabase *db) {
3 [db beginTransaction];
4 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @22];
5 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @23];
6 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @24];
7 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @25];
8 [db commit];
9 }];
事务处理的另一种方式:
1 [self.queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
2 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @22];
3 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @23];
4 [db executeUpdate:@"INSERT INTO t_person (name, age) VALUES (?, ?);",@"wendingding", @24];
5 }];