iOS Development : Truy xuất SQLite dễ dàng với FMDB

Published by Việt Coding on

Xin chào các bạn,

Hôm nay Việt Coding xin giới thiệu đến các bạn thư viện FMDB hỗ trợ các bạn đơn giản hoá trong các thao tác với CSDL SQLite.

FMDB stands for Flying Meat Database. What a great name… This project aims to be a fully featured wrapper for sqlite. You can clone their repository on their github.

SQLite - CSDL thường dùng với các ứng dụng trên iOS

SQLite – CSDL thường dùng với các ứng dụng trên iOS

Trước hết chúng ta cần download FMDB

https://github.com/ccgus/fmdb

Sau khi download và giải nén, chúng ta copy toàn bộ các file trong /src vào project XCode ( trừ file fmdb.m – đây là file chứa unit test có thể gây xung đột với project của chúng ta.

Để các file trong project gọn gàng, bạn có thể tạo một thư mục đặt tên FMDB và di chuyển các file vừa add vào project vào thư mục này.

Đừng quên thêm libsqlite3.0.dylib vào project nhé.

Bây giờ có thể bắt đầu viết code rồi 🙂

1. Khai báo và khởi tạo đối tượng database

FMDatabase *myDb = [FMDatabase databaseWithPath:@"/tmp/test.db"];

Hoặc

databaseFilename = @"test.db";
NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
databasePath = [[NSString alloc] initWithString:[docDir stringByAppendingPathComponent:databaseFilename]];
NSFileManager *fileMgr = [NSFileManager defaultManager];
BOOL exist = [fileMgr fileExistsAtPath:databasePath];
FMDatabase *myDb;

if(exist)
{
myDB = [FMDatabase databaseWithPath:databasePath];
}

2. Truy vấn (SELECT) và lấy dữ liệu

FMResultSet *s = [myDb executeQuery:@"SELECT COUNT(*) FROM myTable"];

while ([s next])
{
//lấy dữ liệu ở đây và đưa vào mảng (ví dụ)
}

FMResultSet cung cấp cho chúng ta một số hàm để lấy các kiểu dữ liệu tương ứng:

- intForColumn:
- longForColumn:
- longLongIntForColumn:
- boolForColumn:
- doubleForColumn:
- stringForColumn:
- dateForColumn:
- dataForColumn:
- dataNoCopyForColumn:
- UTF8StringForColumnIndex:
- objectForColumn:

Ví dụ:

FMResultSet *results = [myDB executeQuery:@"SELECT * FROM myTable"];

while([results next])
{
NSString *name = [results stringForColumn:@"Name"];
NSInteger age = [results intForColumn:@"Age"];
NSLog(@"User: %@ - %d",name, age);
}

[database close];

3. Chèn, Xoá dữ liệu

– Chèn dữ liệu:

NSString *query = [NSString stringWithFormat:@"INSERT INTO myTable VALUES ('%@', %d)",
@"VietCoding", 30];

// execute
[database executeUpdate:query];

Hoặc

[database executeUpdate:@"INSERT INTO myTable (Name, Age) VALUES (?,?)",
@"VietCoding",[NSNumber numberWithInt:30],nil];

– Xoá dữ liệu:

[database executeUpdate:@"DELETE FROM myTable WHERE Age = 30"];



Như các bạn cũng thấy, nhờ có FMDB mà việc thao tác với CSDL SQLite đã đơn giản hơn rất nhiều. Rất hữu ích cho các ứng dụng thiên về CSDL. Nó sẽ giúp bạn tiết kiệm nhiều thời gian hơn so với khi phải dùng trực tiếp các hàm có sẵn trong bộ SDK.

Quảng cáo tài trợ


Việt Coding

Là một người đam mê lập trình, tôi vọc vạch đủ thứ liên quan đến lập trình cho thoả chí tò mò. Hiện làm chủ yếu ở mảng phát triển ứng dụng di động cho iOS và Android với React Native. Thỉnh thoảng vọc vạch mấy thứ liên quan đến Internet of Things như Smart Home. Đang nghịch mấy con Raspberry Pi và thấy nó cũng thú vị :)

1 Comment

mrthang · 22/06/2013 at 10:24

Mình đang dùng thử FMDB. Nhưng có một vấn đề không hiểu là trên iOS 5 thì rất nhanh nhưng trên iOS 6 thì lại rất chậm. Có ai biết nguyên nhân tại sao không? Mình thử với khoảng 100k row.

Leave a Reply to mrthang Cancel reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

To create code blocks or other preformatted text, indent by four spaces:

    This will be displayed in a monospaced font. The first four 
    spaces will be stripped off, but all other whitespace
    will be preserved.
    
    Markdown is turned off in code blocks:
     [This is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

Here is some inline `code`.

For more help see http://daringfireball.net/projects/markdown/syntax