标签:ios objective-c sqlite
// 拼接数据库地址 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]; NSString *sqlFile = [path stringByAppendingPathComponent:@"student.sqlite"]; // 该方法接收一个地址, 它会根据地址创建一个数据, 如果不存在就会自动创建 FMDatabase *db = [FMDatabase databaseWithPath:sqlFile]; if([db open]){ // 创建表 NSString *sql = @"CREATE TABLE IF NOT EXISTS t_student(id INTEGER PRIMARY KEY AUTOINCREMENT , name TEXT, age INTEGER, score REAL);"; // 在FMDB中除了查询以外的操作都称之为更新 if([db executeUpdate:sql]){ NSLog(@"创建表成功"); } }
NSString *sql = @"INSERT INTO t_student(age, score, name) VALUES ('28', 100, 'jonathan');"; if([self.db executeUpdate:sql]) { NSLog(@"插入成功"); }
NSString *sql = @"SELECT * FROM t_student;"; // 查询数据, 会将所有查询到得数据, 放到results中 FMResultSet *results = [self.db executeQuery:sql]; // 从results中获取数据 while ([results next]) { NSString *name = [results stringForColumn:@"name"]; int age = [results intForColumn:@"age"]; double score = [results doubleForColumn:@"score"]; NSLog(@"%@ %d %f", name, age, score); }
// 拼接数据库地址 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]; NSString *sqlFile = [path stringByAppendingPathComponent:@"student.sqlite"]; // 该方法接收一个地址, 它会根据地址创建一个数据, 如果不存在就会自动创建 // 创建一个数据库队列 FMDatabaseQueue *dbQueue = [FMDatabaseQueue databaseQueueWithPath:sqlFile]; //只要调用dbQueue的inDatabase方法, 系统就会传递一个已经打开并且线程安全的数据库给我们 [dbQueue inDatabase:^(FMDatabase *db) { // 创建表 NSString *sql = @"CREATE TABLE IF NOT EXISTS t_student(id INTEGER PRIMARY KEY AUTOINCREMENT , name TEXT, age INTEGER, score REAL);"; if([db executeUpdate:sql]){ NSLog(@"创建表成功"); } }];
[dbQueue inDatabase:^(FMDatabase *db) { NSString *sql = @"SELECT * FROM t_student;"; // 查询数据, 会将所有查询到得数据, 放到results中 FMResultSet *results = [db executeQuery:sql]; // 从results中获取数据 while ([results next]) { NSString *name = [results stringForColumn:@"name"]; int age = [results intForColumn:@"age"]; double score = [results doubleForColumn:@"score"]; NSLog(@"%@ %d %f", name, age, score); } }];
[self.dbQueue inDatabase:^(FMDatabase *db) { // 告诉系统开启事务, 只要开启事务之后, 但凡没有看到提交事务(事务结束), 那么中间执行的任何语句都将无效 [db beginTransaction]; NSString *sql1 = @"UPDATE t_student SET money = 500 WHERE name = 'cx'"; NSString *sql2 = @"UPDATE t_student SET money = 1500 WHERE name = ‘wj'"; [db executeUpdate:sql1]; [db executeUpdate:sql2]; // 提交事务(结束事务) [db commit]; }];
标签:ios objective-c sqlite
原文地址:http://blog.csdn.net/u011058732/article/details/45190073