在ios中,持久化用好几种 方法,前面已经介绍了 两种 ,一个是简单的写入文件,另一个是加入了序列化并写入文件中,现在介绍 ios 中嵌入式数据库sqlite3的初级应用 当然在使用sqlite3之前 你需要将libsqlite3.dylib这个类库加入到你的项目中
//
- (NSString *)dataFilePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; return [documentsDirectory stringByAppendingPathComponent:kFilename];}NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0]; //首先得到应用程序沙盒中Document文件夹的路径return [documentsDirectory stringByAppendingPathComponent:kFilename]//返回你指定文件的路径
//
打开数据库
sqlite3 *database;
if (sqlite3_open([filePath UTF8String], &database)) { sqlite3_close(database); NSAssert(0,@"Failed to open database"); }///
创建数据库
char *errorMsg;
NSString *createSQL = @"CREATE TABLE IF NOT EXISTS FIELDS (ROW INTEGER PRIMARY KEY,FIELD_DATA TEXT);"; if (sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg)!=SQLITE_OK) { sqlite3_close(database); NSAssert1(0,@"Error creating table:%s",errorMsg); } /查询
NSString *query = @"SELECT ROW, FIELD_DATA FROM FIELDS ORDER BY ROW"; sqlite3_stmt *statement; if (sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil)==SQLITE_OK) { while (sqlite3_step(statement)==SQLITE_ROW) { int row = sqlite3_column_int(statement, 0); char *rowData = (char *)sqlite3_column_text(statement, 1); //NSString *fieldName = [[NSString alloc] initWithFormat:@"field&d",row]; //NSString *fieldValue = [[NSString alloc] initWithUTF8String:rowData]; //UITextField *field = [self valueForKey:fieldName]; //field.text = fieldValue; //[fieldName release]; //[fieldValue release]; } sqlite3_finalize(statement); } sqlite3_close(database);插入 更新
sqlite3 *database; if (sqlite3_open([[self dataFilePath] UTF8String], &database)) { sqlite3_close(database); NSAssert(0,@"Failed to open database"); } for (int i=1; i<=4; i++) { NSString *fieldName = [[NSString alloc] initWithFormat:@"field%d",i]; UITextField *field = [self valueForKey:fieldName]; [fieldName release]; char *errorMsg; char *update = "INSERT OR REPLACE INTO FIELDS (ROW,FIELD_DATA) VALUES(?,?);"; //这里插入的值可以用nsstring替换,但是最好的做法是使用绑定,如果遇到特殊字符 这是不二选择 sqlite3_stmt *stmt; if (sqlite3_prepare_v2(database, update, -1, &stmt, nil)==SQLITE_OK) { sqlite3_bind_int(stmt, 1, i); sqlite3_bind_text(stmt, 2, [[field text] UTF8String], -1, NULL); } if (sqlite3_step(stmt)!=SQLITE_DONE) { NSAssert(0,@"Error updating table:%s",errorMsg); } sqlite3_finalize(stmt); } sqlite3_close(database);这是最基础的sqlite3在ios中的应用 方法的具体应用请查询文档
posted on 2012-03-12 11:41 阅读( ...) 评论( ...)