iOS使用SQLite编程

因为自己以前接触过SQL Server,基于SQL命令的相同,所以就选择SQLite做本地存储,而没有用coreData、XML/plist、或其他什么?

先要导入Framework库:libsqlite3.0.dylib, 头文件调用#import <sqlite3.h>,再定义个全局变量sqlite3 *database 作为数据库对象。准备工作完成!

核心代码如下,了解Sql的人同能理解什么意思。

1    -(void) QueryTable;
2    {
3        // Setup the database object
4        sqlite3 *database;
5        catalogMenus = [[NSMutableArray alloc] init];
6        // Open the database from the users filessytem
7        if(sqlite3_open([[appDelegate getDBPath:dbName] UTF8String], &database) == SQLITE_OK)
01            // Setup the SQL Statement and compile it for faster access
02            const char *sqlStatement = “select * from table_catalogs”;
03            sqlite3_stmt *compiledStatement;
04            if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK)        // Loop through the results and add them to the feeds array
05            while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
06               // Read the data from the result row
07               NSMutableString *ID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
08               NSMutableString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
09               NSMutableString *pic = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
10
view source
print?
01               // add catalog to menus
02               Category *catalog = [Category catalogsWithUID:ID name:name thumb:pic];
03              [catalogMenus addObject:catalog];
04            }
05        }
06        // Release the compiled statement from memory
07        sqlite3_finalize(compiledStatement);
08    }
09        // Important To Print Out Values for Objects
10        for (Category *itm in catalogMenus)
11       {
12         NSLog(@”id:%@, name:%@”,itm.categoryID, itm.categoryName);
13       }
14        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@”id” ascending:YES];
15        NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
16        NSArray *sortedArray = [catalogMenus sortedArrayUsingDescriptors:sortDescriptors];
17        catalogMenus = [sortedArray mutableCopy];
18
19        sqlite3_close(database);
20    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值