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 }