FMDB的增删改查操作:
创建表:
- if ([db open]) {
- NSString *sqlCreateTable = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' ('%@' INTEGER PRIMARY KEY AUTOINCREMENT, '%@' TEXT, '%@' INTEGER, '%@' TEXT)",TABLENAME,ID,NAME,AGE,ADDRESS];
- BOOL res = [db executeUpdate:sqlCreateTable];
- if (!res) {
- NSLog(@"error when creating db table");
- } else {
- NSLog(@"success to creating db table");
- }
- [db close];
- }
添加数据:
- if ([db open]) {
- NSString *insertSql1= [NSString stringWithFormat:
- @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
- TABLENAME, NAME, AGE, ADDRESS, @"张三", @"13", @"济南"];
- BOOL res = [db executeUpdate:insertSql1];
- NSString *insertSql2 = [NSString stringWithFormat:
- @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES ('%@', '%@', '%@')",
- TABLENAME, NAME, AGE, ADDRESS, @"李四", @"12", @"济南"];
- BOOL res2 = [db executeUpdate:insertSql2];
- if (!res) {
- NSLog(@"error when insert db table");
- } else {
- NSLog(@"success to insert db table");
- }
- [db close];
- }
修改数据:
- if ([db open]) {
- NSString *updateSql = [NSString stringWithFormat:
- @"UPDATE '%@' SET '%@' = '%@' WHERE '%@' = '%@'",
- TABLENAME, AGE, @"15" ,AGE, @"13"];
- BOOL res = [db executeUpdate:updateSql];
- if (!res) {
- NSLog(@"error when update db table");
- } else {
- NSLog(@"success to update db table");
- }
- [db close];
- }
删除数据:
- if ([db open]) {
- NSString *deleteSql = [NSString stringWithFormat:
- @"delete from %@ where %@ = '%@'",
- TABLENAME, NAME, @"张三"];
- BOOL res = [db executeUpdate:deleteSql];
- if (!res) {
- NSLog(@"error when delete db table");
- } else {
- NSLog(@"success to delete db table");
- }
- [db close];
- }
数据库查询操作:
查询操作使用了executeQuery,并涉及到FMResultSet。
- if ([db open]) {
- NSString * sql = [NSString stringWithFormat:
- @"SELECT * FROM %@",TABLENAME];
- FMResultSet * rs = [db executeQuery:sql];
- while ([rs next]) {
- int Id = [rs intForColumn:ID];
- NSString * name = [rs stringForColumn:NAME];
- NSString * age = [rs stringForColumn:AGE];
- NSString * address = [rs stringForColumn:ADDRESS];
- NSLog(@"id = %d, name = %@, age = %@ address = %@", Id, name, age, address);
- }
- [db close];
- }