在iPhone上是採用sqlite進行數據存儲是我一種比較習慣性的做法。一般在其他平臺也比較習慣用sqlite,比如android。
而iphone上有一些封裝好的第三方框架提供使用,更節省了許多時間。如:Sqlitepersistentobjects ,FMDB。今天查找了這個兩個框架,感覺FMDB的風格更符合我的使用,其實兩者是各有優點的,只是看個人喜好而已。
以下是FMDB的一些基本使用,FMDB框架其實只是一層很薄的封裝,主要的類也就兩個:FMDatabase和FMResultSet;
其中的FMResultSet對象讓我想起了android中sqlite的cursor集合啊。
FMDB的github地址是,https://github.com/ccgus/fmdb。
1、首先得實例化一個FMDatabase對象,這跟Sqlitepersistentobjects 派生一個子類進行操作是不同。接着打開一個數據庫(如果沒有會創建一個數據庫)
- //paths: ios下Document路徑,Document爲ios中可讀寫的文件夾
- NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
- NSString *documentDirectory = [paths objectAtIndex:0];
- //dbPath: 數據庫路徑,在Document中。
- NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"Test.db"];
- //創建數據庫實例 db 這裏說明下:如果路徑中不存在"Test.db"的文件,sqlite會自動創建"Test.db"
- FMDatabase *db= [FMDatabase databaseWithPath:dbPath] ;
- if (![db open]) {
- NSLog(@"Could not open db.");
- return ;
- }
接下來,我們可以通過這個數據庫對象進行操作了。操作主要是update和queries。
首先是創建表。
- //創建一個名爲User的表,有兩個字段分別爲string類型的Name,integer類型的 Age
-
[db executeUpdate:@
"CREATE TABLE PersonList (Name text, Age integer, Sex integer, Phone text, Address text, Photo blob)"
];
-
這是FMDB裡很常用的指令,[FMDatabase_object
executeUpdate:]後面用NSString塞入SQLite語法,就解決了。因為這篇主要是在講FMDB,所以SQLite的語法就不多說了,上述程式碼建立了一個名為PersonList的table,裡面有姓名、年齡、性別、電話、地址和照片。(嗯….很範例的一個table)
這樣我們就有了一張表了。接下我們對錶進行操作。插入數據!注意插入的數據使用了通配符,這跟iphone直接使用sqlite藉口的綁定變量是一樣的,後面的通配符匹配的數據。
- //插入數據使用OC中的類型 text對應爲NSString integer對應爲NSNumber的整形
-
2
[db executeUpdate:@
"INSERT INTO PersonList (Name, Age, Sex, Phone, Address, Photo) VALUES (?,?,?,?,?,?)"
,
@
"Jone"
,
-
[NSNumber numberWithInt:20], [NSNumber numberWithInt:0], @“091234567”, @“Taiwan, R.O.C”,
-
[NSData dataWithContentsOfFile: filepath]];
接下來是更新數據。
- //更新數據
-
[db executeUpdate:@
"UPDATE PersonList SET Age = ? WHERE Name = ?"
,[NSNumber numberWithInt:30],@“John”];
再接下來,就是刪除數據啦。
- //刪除數據
- [db executeUpdate:@"DELETE FROM User WHERE Name = ?",@"老婆"];
FMResultSet
*rs = [db executeQuery:@
"SELECT
Name, Age, FROM PersonList"
];
while
([rs
next]) {
NSString
*name = [rs stringForColumn:@
"Name"
];
int
age = [rs intForColumn:@
"Age"
];
}
[rs
close];
用[rs
next]可以輪詢query回來的資料,每一次的next可以得到一個row裡對應的數值,並用[rs stringForColumn:]或[rs intForColumn:]等方法把值轉成Object-C的型態。取用完資料後則用[rs close]把結果關閉。
update的基本操作就這幾個,接下來是queries!
- //返回數據庫中第一條滿足條件的結果
- NSString *aa=[db stringForQuery:@"SELECT Name FROM User WHERE Age = ?",@"20"];
這樣我們就查詢返回了一條數據,那當我們想要查詢放返回多條數據怎麼辦呢?不用愁,之前我就提到了FMDB中的另外一個主要的類,FMResultSet,這是一個結果集!返回多條數據時FMDB會將數據放在這個結果集中,然後我們在對這個結果集進行查詢操作!很簡單。
- FMResultSet *rs=[db executeQuery:@"SELECT * FROM User"];
- rs=[db executeQuery:@"SELECT * FROM User WHERE Age = ?",@"20"];
- while ([rs next]){
- NSLog(@"%@ %@",[rs stringForColumn:@"Name"],[rs stringForColumn:@"Age"]);
- }
更多的FMResultSet方法有:
intForColumn:
longForColumn:
longLongIntForColumn:
boolForColumn:
doubleForColumn:
stringForColumn:
dateForColumn:
dataForColumn:
dataNoCopyForColumn:
UTF8StringForColumnIndex:
objectForColumn:
具體查看一下類就行了!好了,對於FMDB的使用就這樣,是不是很簡單呢,其實這個些封裝sqlite的框架都是萬變不離其宗的,只要你掌握了sql就行了!
其他:http://www.w2bc.com/Article/18028
http://www.tuicool.com/articles/Mbaui2
iOS中原生的SQLite API在使用上相當不友好,在使用時,非常不便。於是,就出現了一系列將SQLite API進行封裝的庫,例如FMDB、PlausibleDatabase、sqlitepersistentobjects等,FMDB
(https://github.com/ccgus/fmdb) 是一款簡潔、易用的封裝庫,這一篇文章簡單介紹下FMDB的使用。
在FMDB下載文件後,工程中必須導入如下文件,並使用 libsqlite3.dylib 依賴包。
FMDB同時兼容ARC和非ARC工程,會自動根據工程配置來調整相關的內存管理代碼。
FMDB常用類:
FMDatabase : 一個單一的SQLite數據庫,用於執行SQL語句。
FMResultSet :執行查詢一個FMDatabase結果集,這個和android的Cursor類似。
FMDatabaseQueue :在多個線程來執行查詢和更新時會使用這個類。
創建數據庫:
- db = [FMDatabase databaseWithPath:database_path];
1、當數據庫文件不存在時,fmdb會自己創建一個。
2、 如果你傳入的參數是空串:@"" ,則fmdb會在臨時文件目錄下創建這個數據庫,數據庫斷開連接時,數據庫文件被刪除。
3、如果你傳入的參數是 NULL,則它會建立一個在內存中的數據庫,數據庫斷開連接時,數據庫文件被刪除。
打開數據庫:
- [db open]
返回BOOL型。
關閉數據庫:
- [db close]
數據庫增刪改等操作:
除了查詢操作,FMDB數據庫操作都執行executeUpdate方法,這個方法返回BOOL型。
創建表:
- 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];
- }
數據庫多線程操作:
如果應用中使用了多線程操作數據庫,那麼就需要使用FMDatabaseQueue來保證線程安全了。 應用中不可在多個線程中共同使用一個FMDatabase對象操作數據庫,這樣會引起數據庫數據混亂。 爲了多線程操作數據庫安全,FMDB使用了FMDatabaseQueue,使用FMDatabaseQueue很簡單,首先用一個數據庫文件地址來初使化FMDatabaseQueue,然後就可以將一個閉包(block)傳入inDatabase方法中。 在閉包中操作數據庫,而不直接參與FMDatabase的管理。
- FMDatabaseQueue * queue = [FMDatabaseQueue databaseQueueWithPath:database_path];
- dispatch_queue_t q1 = dispatch_queue_create("queue1", NULL);
- dispatch_queue_t q2 = dispatch_queue_create("queue2", NULL);
- dispatch_async(q1, ^{
- for (int i = 0; i < 50; ++i) {
- [queue inDatabase:^(FMDatabase *db2) {
- NSString *insertSql1= [NSString stringWithFormat:
- @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
- TABLENAME, NAME, AGE, ADDRESS];
- NSString * name = [NSString stringWithFormat:@"jack %d", i];
- NSString * age = [NSString stringWithFormat:@"%d", 10+i];
- BOOL res = [db2 executeUpdate:insertSql1, name, age,@"濟南"];
- if (!res) {
- NSLog(@"error to inster data: %@", name);
- } else {
- NSLog(@"succ to inster data: %@", name);
- }
- }];
- }
- });
- dispatch_async(q2, ^{
- for (int i = 0; i < 50; ++i) {
- [queue inDatabase:^(FMDatabase *db2) {
- NSString *insertSql2= [NSString stringWithFormat:
- @"INSERT INTO '%@' ('%@', '%@', '%@') VALUES (?, ?, ?)",
- TABLENAME, NAME, AGE, ADDRESS];
- NSString * name = [NSString stringWithFormat:@"lilei %d", i];
- NSString * age = [NSString stringWithFormat:@"%d", 10+i];
- BOOL res = [db2 executeUpdate:insertSql2, name, age,@"北京"];
- if (!res) {
- NSLog(@"error to inster data: %@", name);
- } else {
- NSLog(@"succ to inster data: %@", name);
- }
- }];
- }
- });