Friday 1 March 2013

Use FMDB for iPhone


FMDB is an Objective-C wrapper of the Sqlite used in the iPhone. Instead of writing similar functions in C/C++ or Objective-C, this wrapper provides a quick and easy way to work with Sqlite.

FMDB source code download:
https://github.com/ccgus/fmdb

Examples:

1. Open a database:
?
1
FMDatabase* db = [FMDatabase databaseWithPath:@"/tmp/tmp.db"];

2. Create a table:
?
1
[db executeUpdate:@"create table test (id integer, name text, description text);"];

3. Insert a record:
?
1
2
3
4
5
6
[db beginTransaction];
[db executeUpdate:@"insert into test (id, name, description) values (?, ?, ?);" ,
    [NSNumber numberWithInt:1],
    @"Test'",
    @"This is a test'"];
[db commit];

4. Update a record:
?
1
2
3
4
5
[db beginTransaction];
[db executeUpdate:@"update test set name = ? where id = ?;" ,
    @"New Test'",
    1];
[db commit];

5. Retrieve a record set:
?
1
2
3
4
5
6
7
8
FMResultSet* rs = [db executeQuery:@"select * from test;"];
while ([rs next]) {
    NSLog(@"Id = %d, Name = %@, Description = %@",
    [rs intForColumn:@"id"],
    [rs stringForColumn:@"name"],
    [rs stringForColumn:@"description"]);
}       
[rs close];

6. Delete a table:
?
1
[db executeUpdate:@"drop table test;"];

No comments:

Post a Comment